如何解决使用值声明指针的正确方法
我想学习C语言中的指针的基础知识
以下两种方式有什么区别?哪个是正确的?哪个更合适?
int a = 20;
int *p = &a ;
或
int a = 20;
int *p ;
p = &a ;
解决方法
这里的区别与指针无关,但通常与声明和初始化变量有关。
例如,您可以执行以下操作:
int a; // this declares the variable a as an integer
a = 20; // this initializes the variable a with the value 20.
或者,您可以将这两部分合并为一行:
int a = 20; //this now both declares and initializes the variable a.
区别在于,您只能声明一个变量ONCE,但可以根据需要多次为其分配一个值。
所以如果你要写
int a = 20;
然后在您的代码中稍后要更改a的值,例如30,在这里您只能编写
a = 30;
您无法再次写入int a = 30;
,因为您无法再次声明{,而a已经被声明。
这种差异就是您用指针说明的。
int a = 20; //variable a is declared as an int and also initialized to the value 20
int *p = &a ; //pointer p is declared and initialized with the address of a.
or
int a = 20; // variable a is declared as an int and also initialized to the value of 20
int *p ; // pointer p is declared
p = &a ; // pointer p is assigned the value that is the address of variable a.
您也可以写
int a;
a = 20;
int *p;
p = &a;
这仍然是正确的,并且会产生完全相同的结果。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。