首页 > 解决方案 > 用值声明指针的正确方法

问题描述

我想学习非常基础的 C 语言指针

以下两种方式有什么区别?哪个是对的?哪个更可取?

int a = 20;
int *p = &a ;

或者

int a = 20;
int *p ;
p = &a ;

标签: cpointers

解决方案


这里的区别与指针无关,但通常与声明和初始化变量有关。

例如,您可以这样做:

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;

这仍然是正确的,并且产生完全相同的结果。


推荐阅读