You are on page 1of 3

ใบงานที่ 5

Structure and Pointer


รหัสนศ. 116630462036-0 ชื่อ สกุล นายณัฐชัย ยิ้มฉาย กลุ่ม 1 .
วัตถุประสงค์์ ศึกษาและเพิม่ ทักษะ การเขียนโปรแกรมด้วยตัวแปรแบบโครงสร้างและพอยต์เตอร์
การทดลองที1่ จงเขียนโปรแกรมเก็บข้อมูลพนักงานจํานวน 10 คน โดยมี รายละเอียดดังนี้
– ข้อมูลประกอบด้วย ชื่อกับ เงินเดือน – รับข้อมูลพนักงานจาก keyboard – โปรแกรมจะต้องใช้ structure array – เมื่อ
ป้อนข้อมูลเสร็จ โปรแกรมจะค้นหาพนักงานทีม่ ีเงินเดือนมากกว่า 20,000 บาท แสดงชื่อ ออกจอภาพ
#include<stdio.h> Output
#include<conio.h> Employee Salary
#include<string.h> ===============
int main() Enter Name 1 : Somchai
{ int i; Enter Salary 1 : 9000
int j=0; Enter Name 2 : Somying
typedef struct { Enter Salary 2 : 25000
char name[10]; …
int salary; …
} employee; …
employee epy[10]; Enter Name 10 : Nadeach
printf("Employee Salary\n"); Enter Salary 10 : 30000
printf("==================\n");
for(i=0;i<10;i++){ =================
printf("Enter Name %d: ",i+1); Employee Salary > 20000
scanf("%s",epy[i].name); 1. Somying
printf("Enter Salary: "); 2. Nadeach
scanf("%d",&epy[i].salary);
}

printf("==================\n\n\n");
printf("Employee Salary >20000\n");

for(i=0;i<10;i++)
if(epy[i].salary>20000)
printf("%d. %s\n",j=j+1,epy[i].name);
}
การทดลองที่ 2 ให้ลองรัน step ตามตัวอย่างโปรแกรม และทําความเข้าใจตามทฤษฎี
ทฤษฎี pointer type Address int x = 520;
1. Pointer Type เก็บ address ของข้อมูล มีการ int y = 950;
กําหนดค่าตัวแปรดังนี้ int *iPtr1 = &x;
Int *p; // p เก็บ address ของ int int *iPtr2;
Char *q; // q เก็บ address ของ char *iPtr1 = 10;
struct node *r; // r เก็บ address ของ struct iPtr1 = &y;
node *iPtr1 = 20;
2. (&) ให้ค่า address ของ operand iPtr2 = &y;
3. (*) ไปยัง address ที่เก็บไว้ ใน operand *iPtr2 = 30;

เมื่อรันโปรแกรม ค่า x= 10 y = 30 iPtr1 = 62fe10 iPtr2 = 62fe14 &x = 62fe14 &iptr2 = 62fe8

การทดลองที่ 3 สร้างตัวแปรแบบโครงสร้างเพื่อทำงาน โดยมีรูปแบบดังนี้


1. ข้อมูลชื่อ 2. ข้อมูล อายุ
#include <stdio.h> Output
#include <stdlib.h> Insert name A: somchai
int main(void) { Insert age A: 18
typedef struct node {
char name[20]; Insert name B: sompong
int age; Insert age B: 17
} type_node;
typedef struct node *nodeptr; ========
nodeptr a, b, c, d, n; Name Age
a = (nodeptr)malloc(sizeof(type_node)); ========
printf("Insert Name : "); Somchai 18
scanf("%s", a->name); Somping 17
printf("Insert Age : ");
scanf("%d", &a->age);
b = (nodeptr)malloc(sizeof(type_node)); Delete somchai
printf("Insert Name : "); Delete sompong
scanf("%s", b->name);
printf("Insert Age : ");
scanf("%d", &b->age);
printf("============\nName
Age\n============\n");
printf("%s %d\n", a->name, a->age);
printf("%s %d\n", b->name, b->age);
printf("Delete %s\n", a->name);
free(a);
printf("Delete %s\n", b->name);
free(b);
return 0;
}

You might also like