3.6 - סטראקטים - פתרון
פתרון – Struct ו־Union¶
סעיף 1 – יצירת struct פשוט¶
#include <stdio.h>
struct Student {
char* name;
int age;
float avg;
};
int main() {
struct Student s1;
s1.name = "Amit";
s1.age = 21;
s1.avg = 89.5;
printf("Name: %s\n", s1.name);
printf("Age: %d\n", s1.age);
printf("Average: %.2f\n", s1.avg);
return 0;
}
סעיף 2 – העתקת struct¶
struct Student s2 = s1;
printf("Copied student:\n");
printf("Name: %s\n", s2.name);
printf("Age: %d\n", s2.age);
printf("Average: %.2f\n", s2.avg);
s1.age = 30;
printf("s1 age: %d\n", s1.age);
printf("s2 age: %d\n", s2.age); // stays 21, because the copy is by value
סעיף 3 – struct בתוך struct¶
struct Date {
int day;
int month;
int year;
};
struct Student {
char* name;
int age;
float avg;
struct Date birth_date;
};
int main() {
struct Student s1;
s1.name = "Amit";
s1.age = 21;
s1.avg = 89.5;
s1.birth_date.day = 3;
s1.birth_date.month = 7;
s1.birth_date.year = 2002;
printf("Birth date: %02d/%02d/%d\n",
s1.birth_date.day,
s1.birth_date.month,
s1.birth_date.year);
return 0;
}
סעיף 4 – שימוש ב־union¶
union Data {
int i;
float f;
char* str;
};
int main() {
union Data d;
d.i = 1234;
printf("int: %d\n", d.i);
d.f = 4.5;
printf("float: %f\n", d.f);
printf("int again: %d\n", d.i); // will be garbage, because float overwrote the memory
return 0;
}
ה־union חולק את אותו תא זיכרון בין כל המשתנים, לכן רק השדה האחרון שהוגדר יהיה תקף.
סעיף 5 – sizeof ובדיקת גדלים¶
printf("Size of Student: %lu\n", sizeof(struct Student));
printf("Size of Data: %lu\n", sizeof(union Data));
-
גודל struct הוא סכום כל השדות (כולל padding – מרווחים פנימיים שהמחשב מוסיף).
-
גודל union הוא גודל השדה הכי גדול.
סעיף בונוס – סדר משפיע על גודל struct¶
struct A {
char c;
int i;
};
struct B {
int i;
char c;
};
printf("Size of A: %lu\n", sizeof(struct A)); // usually 8
printf("Size of B: %lu\n", sizeof(struct B)); // usually also 8, but sometimes less depending on alignment
// reason: padding - to align the variables per the processor's requirement, empty bytes are added.