8.7 พอยน์เตอร์กับข้อมูลแบบโครงสร้าง (pointer and structures) หัวข้อนี้จะมีประโยชน์มากเมื่อต้องการทำโครงสร้างข้อมูลแบบ linked list และ tree แบบต่าง ๆ การใช้พอยน์เตอร์อ้างอิงตัวแปรภายในข้อมูลแบบโครงสร้าง สามารถทำได้ดังนี้
รูปแบบการใช้พอยน์เตอร์อ้างอิงตัวแปรภายในข้อมูลแบบโครงสร้าง
(*ptr_name).member_var
หรือ
ptr_name->member_var
เพื่อความเข้าใจเกี่ยวกับการใช้พอยน์เตอร์อ้างอิงตัวแปรภายในข้อมูลแบบโครงสร้าง มากยิ่งขึ้น ให้ศึกษาจากโปรแกรมตัวอย่างดังต่อไปนี้โปรแกรมตัวอย่างที่ 8.7 แสดงการใช้พอยน์เตอร์อ้างอิงตัวแปรภายในข้อมูลแบบโครงสร้าง
 |  | |  |  |
|
/* ptrstru.c */ #include<stdio.h> /* บรรทัดที่ 1 */ #include<conio.h> /* บรรทัดที่ 2 */ void main(void) /* บรรทัดที่ 3 */ { /* บรรทัดที่ 4 */ struct x /* บรรทัดที่ 5 */ { /* บรรทัดที่ 6 */ int num; /* บรรทัดที่ 7 */ char ch; /* บรรทัดที่ 8 */ }; /* บรรทัดที่ 9 */ struct x one; /* บรรทัดที่ 10 */ struct x *ptr; /* define pointer to structure */ /* บรรทัดที่ 11 */ clrscr(); /* บรรทัดที่ 12 */ ptr = &one; /* assign address of struc to ptr */ /* บรรทัดที่ 13 */ ptr->num = 230; /* or ptr.num = 230 */ /* บรรทัดที่ 14 */ ptr->ch = 'K'; /* or ptr.ch = 'K' */ /* บรรทัดที่ 15 */ printf("\nNumber = %d\n",ptr->num); /* บรรทัดที่ 16 */ printf("Char = %c", ptr->ch); /* บรรทัดที่ 17 */ printf("\n\nPress any key back to program..."); /* บรรทัดที่ 18 */ getch(); /* บรรทัดที่ 19 */ } /* บรรทัดที่ 20 */ | |
 | |  |
ผลลัพธ์ที่ได้จากโปรแกรม
0 ความคิดเห็น:
แสดงความคิดเห็น