ปัญหา
เขียนโปรแกรม C เพื่อกำหนดโครงสร้างและแสดงขนาดและออฟเซ็ตของตัวแปรสมาชิก
โครงสร้าง − เป็นชุดของตัวแปรประเภทข้อมูลต่างๆ รวมกันเป็นชื่อเดียว
รูปแบบทั่วไปของการประกาศโครงสร้าง
datatype member1;
struct tagname{
datatype member2;
datatype member n;
}; ที่นี่ struct - คำหลัก
tagname - ระบุชื่อโครงสร้าง
member1, member2 - ระบุรายการข้อมูลที่ประกอบเป็นโครงสร้าง
ตัวอย่าง
struct book{
int pages;
char author [30];
float price;
}; ตัวแปรโครงสร้าง
การประกาศตัวแปรโครงสร้างมีสามวิธี -
วิธีที่ 1
struct book{
int pages;
char author[30];
float price;
}b; วิธีที่ 2
struct{
int pages;
char author[30];
float price;
}b; วิธีที่ 3
struct book{
int pages;
char author[30];
float price;
};
struct book b; การเริ่มต้นและการเข้าถึงโครงสร้าง
การเชื่อมโยงระหว่างสมาชิกและตัวแปรโครงสร้างถูกสร้างขึ้นโดยใช้ตัวดำเนินการสมาชิก (หรือ) ตัวดำเนินการจุด
การเริ่มต้นสามารถทำได้ด้วยวิธีต่อไปนี้ -
วิธีที่ 1
struct book{
int pages;
char author[30];
float price;
} b = {100, "balu", 325.75}; วิธีที่ 2
struct book{
int pages;
char author[30];
float price;
};
struct book b = {100, "balu", 325.75}; วิธีที่ 3 (โดยใช้ตัวดำเนินการสมาชิก)
struct book{
int pages;
char author[30];
float price;
} ;
struct book b;
b. pages = 100;
strcpy (b.author, "balu");
b.price = 325.75; วิธีที่ 4 (โดยใช้ฟังก์ชัน scanf)
struct book{
int pages;
char author[30];
float price;
} ;
struct book b;
scanf ("%d", &b.pages);
scanf ("%s", b.author);
scanf ("%f", &b. price); ประกาศโครงสร้างด้วยสมาชิกข้อมูลและพยายามพิมพ์ค่าออฟเซ็ตและขนาดของโครงสร้าง
โปรแกรม
#include<stdio.h>
#include<stddef.h>
struct tutorial{
int a;
int b;
char c[4];
float d;
double e;
};
int main(){
struct tutorial t1;
printf("the size 'a' is :%d\n",sizeof(t1.a));
printf("the size 'b' is :%d\n",sizeof(t1.b));
printf("the size 'c' is :%d\n",sizeof(t1.c));
printf("the size 'd' is :%d\n",sizeof(t1.d));
printf("the size 'e' is :%d\n",sizeof(t1.e));
printf("the offset 'a' is :%d\n",offsetof(struct tutorial,a));
printf("the offset 'b' is :%d\n",offsetof(struct tutorial,b));
printf("the offset 'c' is :%d\n",offsetof(struct tutorial,c));
printf("the offset 'd' is :%d\n",offsetof(struct tutorial,d));
printf("the offset 'e' is :%d\n\n",offsetof(struct tutorial,e));
printf("size of the structure tutorial is :%d",sizeof(t1));
return 0;
} ผลลัพธ์
the size 'a' is :4 the size 'b' is :4 the size 'c' is :4 the size 'd' is :4 the size 'e' is :8 the offset 'a' is :0 the offset 'b' is :4 the offset 'c' is :8 the offset 'd' is :12 the offset 'e' is :16 size of the structure tutorial is :24