ตัวชี้เป็นตัวแปรที่เก็บที่อยู่ของตัวแปรอื่น
คุณสมบัติของพอยน์เตอร์
-
ตัวชี้ช่วยประหยัดพื้นที่หน่วยความจำ
-
เวลาดำเนินการของตัวชี้เร็วขึ้นเนื่องจากการเข้าถึงตำแหน่งหน่วยความจำโดยตรง
-
ด้วยความช่วยเหลือของพอยน์เตอร์ หน่วยความจำจะเข้าถึงได้อย่างมีประสิทธิภาพ กล่าวคือ หน่วยความจำได้รับการจัดสรรและจัดสรรคืนแบบไดนามิก
-
พอยน์เตอร์ใช้กับโครงสร้างข้อมูล
การประกาศตัวชี้
int *p;
หมายความว่า 'p' เป็นตัวแปรตัวชี้ที่เก็บที่อยู่ของตัวแปรจำนวนเต็มอื่น
การเริ่มต้นของตัวชี้
ตัวดำเนินการที่อยู่ (&) ใช้เพื่อเริ่มต้นตัวแปรตัวชี้
ตัวอย่างเช่น
int qty = 175; int *p; p= &qty;

การเข้าถึงตัวแปรผ่านตัวชี้
ในการเข้าถึงค่าของตัวแปร จะใช้ตัวดำเนินการทางอ้อม (*)
โปรแกรม
#include<stdio.h>
void main(){
//Declaring variables and pointer//
int a=2;
int *p;
//Declaring relation between variable and pointer//
p=&a;
//Printing required example statements//
printf("Size of the integer is %d\n",sizeof (int));//4//
printf("Address of %d is %d\n",a,p);//Address value//
printf("Value of %d is %d\n",a,*p);//2//
printf("Value of next address location of %d is %d\n",a,*(p+1));//Garbage value from (p+1) address//
printf("Address of next address location of %d is %d\n",a,(p+1));//Address value +4//
//Typecasting the pointer//
//Initializing and declaring character data type//
//a=2 = 00000000 00000000 00000000 00000010//
char *p0;
p0=(char*)p;
//Printing required statements//
printf("Size of the character is %d\n",sizeof(char));//1//
printf("Address of %d is %d\n",a,p0);//Address Value(p)//
printf("Value of %d is %d\n",a,*p0);//First byte of value a - 2//
printf("Value of next address location of %d is %d\n",a,*(p0+1));//Second byte of value a - 0//
printf("Address of next address location of %d is %d\n",a,(p0+1));//Address value(p)+1//
} ผลลัพธ์
Size of the integer is 4 Address of 2 is 6422028 Value of 2 is 2 Value of next address location of 2 is 10818512 Address of next address location of 2 is 6422032 Size of the character is 1 Address of 2 is 6422028 Value of 2 is 2 Value of next address location of 2 is 0 Address of next address location of 2 is 6422029