编写一个展示指针示例的 C 程序
指针是指向另一个变量的地址的变量。
指针的特征
指针可节省内存空间。
由于直接访问内存位置,指针执行速度更快。
借助指针,可以有效地访问内存,即动态地分配和释放内存。
指针与数据结构一起使用。
声明指针
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
",sizeof (int));//4// printf("Address of %d is %d
",a,p);//Address value// printf("Value of %d is %d
",a,*p);//2// printf("Value of next address location of %d is %d
",a,*(p+1));//Garbage value from (p+1) address// printf("Address of next address location of %d is %d
",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
",sizeof(char));//1// printf("Address of %d is %d
",a,p0);//Address Value(p)// printf("Value of %d is %d
",a,*p0);//First byte of value a - 2// printf("Value of next address location of %d is %d
",a,*(p0+1));//Second byte of value a - 0// printf("Address of next address location of %d is %d
",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
广告