c - 用值声明指针的正确方法
问题描述
我想学习非常基础的 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,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;
这仍然是正确的,并且产生完全相同的结果。
推荐阅读
- python - 如何将 sklearn 和 Keras 中的 GridSearchCV 与并行作业相结合而不会泄漏内存
- reactjs - 如何在一个变量设置为随机的情况下测试 Apollo 突变?
- java - 在 Windows 上运行 Github 应用程序
- python-3.x - 为什么在 hidapi 包中编写方法不起作用?
- javascript - 当前歌曲在 React JS 中路由到另一个页面时暂停,如何保持播放?
- php - 修复 FPDF 中文本的位置
- ruby-on-rails - 尝试使用 Protobuf 编码消息时出错
- awk - 如何在awk中剪切字段
- python - 如何在基于函数的视图中使用这个 objectmixins?
- lotus-notes - 在未显示所有文档的注释中为文档 UNID 选择@all