โจทย์
กำหนด Struct แล้วแสดงขนาด (sizeof) และตำแหน่งหน่วยความจำ (offset) ของแต่ละสมาชิก
การประกาศ Struct
struct tagname {
datatype member1;
datatype member2;
...
};
วิธีประกาศตัวแปร Struct
- Method 1:
struct book { ... } b; - Method 2:
struct { ... } b;(anonymous) - Method 3:
struct book { ... }; struct book b;
การ Initialize และ Access
- Dot operator:
b.pages = 100; - Init list:
struct book b = {100, "balu", 325.75}; - scanf:
scanf("%d", &b.pages);
โปรแกรมตัวอย่าง: แสดง sizeof และ offsetof
#include <stdio.h>
#include <stddef.h> // สำหรับ offsetof
struct tutorial {
int a; // 4 bytes
int b; // 4 bytes
char c[4]; // 4 bytes
float d; // 4 bytes
double e; // 8 bytes
};
int main() {
struct tutorial t1;
printf("Size of a: %zu\n", sizeof(t1.a)); // 4
printf("Size of b: %zu\n", sizeof(t1.b)); // 4
printf("Size of c: %zu\n", sizeof(t1.c)); // 4
printf("Size of d: %zu\n", sizeof(t1.d)); // 4
printf("Size of e: %zu\n", sizeof(t1.e)); // 8
printf("Offset of a: %zu\n", offsetof(struct tutorial, a)); // 0
printf("Offset of b: %zu\n", offsetof(struct tutorial, b)); // 4
printf("Offset of c: %zu\n", offsetof(struct tutorial, c)); // 8
printf("Offset of d: %zu\n", offsetof(struct tutorial, d)); // 12
printf("Offset of e: %zu\n", offsetof(struct tutorial, e)); // 16
printf("Struct size: %zu\n", sizeof(t1)); // 24 (alignment)
return 0;
}
ผลลัพธ์
Size of a: 4 Size of b: 4 Size of c: 4 Size of d: 4 Size of e: 8 Offset of a: 0 Offset of b: 4 Offset of c: 8 Offset of d: 12 Offset of e: 16 Struct size: 24