ตัวชี้เป็นตัวแปรที่เก็บที่อยู่ของตัวแปรอื่น เราสามารถเก็บค่า Null ไว้ได้โดยใช้ตัวชี้ สามารถเข้าถึงได้โดยใช้รหัสผ่านอ้างอิง นอกจากนี้ ไม่จำเป็นต้องมีการเริ่มต้นในขณะที่ประกาศตัวแปร
ไวยากรณ์สำหรับพอยน์เตอร์มีดังนี้ −
pointer variable= & another variable;
ตัวอย่างเช่น
p =&a;
อัลกอริทึม
อ้างถึงอัลกอริธึมที่ให้ไว้ด้านล่างเพื่อค้นหาจำนวนที่มากที่สุดในอนุกรมโดยใช้ตัวชี้
Step 1: Start Step 2: Declare integer variables Step 3: Declare pointer variables Step 4: Read 3 numbers from console Step 5: Assign each number address to pointer variable Step 6: if *p1 > *p2
- if *p1 > *p3
- print p1 is large
- else
- print p2 is large
โปรแกรม
ต่อไปนี้เป็นโปรแกรม C เพื่อค้นหาจำนวนที่มากที่สุดในอนุกรมโดยใช้พอยน์เตอร์ -
#include <stdio.h>
int main(){
int num1, num2, num3;
int *p1, *p2, *p3;
printf("enter 1st no: ");
scanf("%d",&num1);
printf("enter 2nd no: ");
scanf("%d",&num2);
printf("enter 3rd no: ");
scanf("%d",&num3);
p1 = &num1;
p2 = &num2;
p3 = &num3;
if(*p1 > *p2){
if(*p1 > *p3){
printf("%d is largest ", *p1);
}else{
printf("%d is largest ", *p3);
}
}else{
if(*p2 > *p3){
printf("%d is largest ", *p2);
}else{
printf("%d is largest ", *p3);
}
}
return 0;
} ผลลัพธ์
เมื่อโปรแกรมข้างต้นทำงาน มันจะให้ผลลัพธ์ดังต่อไปนี้ −
Run 1: enter 1st no: 35 enter 2nd no: 75 enter 3rd no: 12 75 is largest Run 2: enter 1st no: 53 enter 2nd no: 69 enter 3rd no: 11 69 is largest