首页 > 后端开发 > C++ > 编写一个C程序,演示指针的示例

编写一个C程序,演示指针的示例

WBOY
发布: 2023-09-21 19:33:02
转载
1047 人浏览过

指针是一个存储另一个变量地址的变量。

指针的特点

  • 指针节省内存空间。

  • 由于直接访问内存位置,指针的执行时间更快。

  • 在指针的帮助下,内存被有效地访问,即动态分配和释放内存。

  • 指针与数据结构一起使用。

声明一个指针

int *p;
登录后复制

这意味着“p”是一个指针变量,它保存另一个整型变量的地址。

指针的初始化

地址运算符(&)用于初始化指针变量。

例如,

int qty = 175;
int *p;
p= &qty;
登录后复制

编写一个C程序,演示指针的示例

通过变量访问变量指针

要访问变量的值,请使用间接运算符 (*)。

程序

 现场演示

#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</p><p>",sizeof (int));//4//
   printf("Address of %d is %d</p><p>",a,p);//Address value//
   printf("Value of %d is %d</p><p>",a,*p);//2//
   printf("Value of next address location of %d is %d</p><p>",a,*(p+1));//Garbage value from (p+1) address//
   printf("Address of next address location of %d is %d</p><p>",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</p><p>",sizeof(char));//1//
   printf("Address of %d is %d</p><p>",a,p0);//Address Value(p)//
   printf("Value of %d is %d</p><p>",a,*p0);//First byte of value a - 2//
   printf("Value of next address location of %d is %d</p><p>",a,*(p0+1));//Second byte of value a - 0//
   printf("Address of next address location of %d is %d</p><p>",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
登录后复制

以上是编写一个C程序,演示指针的示例的详细内容。更多信息请关注PHP中文网其他相关文章!

相关标签:
来源:tutorialspoint.com
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板