Structure คือการรวมตัวแปรชนิดข้อมูลต่างๆ ไว้ด้วยกันภายใต้ชื่อเดียว
การประกาศและเริ่มต้น Structure
struct tagname {
datatype member1;
datatype member2;
...
};
ตัวอย่าง:
struct book {
int pages;
char author[30];
float price;
};
วิธีประกาศตัวแปร Structure
struct book { ... } b;struct { ... } b;(ไม่มี tagname)struct book { ... }; struct book b;
การเริ่มต้นค่าและเข้าถึงสมาชิก
ใช้ dot operator (.)
วิธีที่ 1: เริ่มต้นทันที
struct book b = {100, "balu", 325.75};
วิธีที่ 2: ใช้ struct แยก
struct book { int pages; char author[30]; float price; };
struct book b = {100, "balu", 325.75};
วิธีที่ 3: กำหนดค่าแต่ละตัว (dot operator)
struct book b;
b.pages = 100;
strcpy(b.author, "balu");
b.price = 325.75;
วิธีที่ 4: ใช้ scanf รับค่า
struct book b;
scanf("%d", &b.pages);
scanf("%s", b.author);
scanf("%f", &b.price);
ตัวอย่างโปรแกรมสมบูรณ์
#include <stdio.h>
struct aaa {
struct aaa *prev;
int i;
struct aaa *next;
};
main() {
struct aaa abc, def, ghi, jkl;
int x = 100;
abc.i = 0; abc.prev = &jkl; abc.next = &def;
def.i = 1; def.prev = &abc; def.next = &ghi;
ghi.i = 2; ghi.prev = &def; ghi.next = &jkl;
jkl.i = 3; jkl.prev = &ghi; jkl.next = &abc;
x = abc.next->next->prev->next->i;
printf("%d", x);
}
ผลลัพธ์
2