我想知道是否有其他方法可以为指针分配指向其值的地址.例如,通常的方法是:
int a = 10;
int *ptr;
ptr = &a;
Run Code Online (Sandbox Code Playgroud)
但在某些地方,我看到它宣称:
int *ptr = &a;
Run Code Online (Sandbox Code Playgroud)
这两种方式都是等价的吗?我有点困惑,因为我一直认为*ptr给出a的值,而不是地址.有人可以解释一下吗?谢谢.
我有点困惑,因为我一直认为
*ptr给出的价值a,而不是地址.
它确实有点令人困惑,因为*它用于声明指针,也用作解引用运算符.实际含义*取决于上下文 - 是否用于声明,初始化或赋值.
值得了解1)声明,2)初始化和3)赋值之间的区别.
int *ptr; // 1) this is declaration without initialisation.
int *ptr = &a; // 2) this is declaration **and** initialisation (initialise ptr to the address of variable a)
int b = 10;
*ptr = b; // 3) this is assignment, assign what pointed by ptr to value of variable b.
Run Code Online (Sandbox Code Playgroud)
*手段(但它尚未指向任何有效位置).ptrint*该装置ptr是一个指向int,并且其初始值是可变的地址a.*是取消引用运算符,即指定ptr变量值指向的内容b.