为指针分配地址

QPT*_*PTR 6 c c++ pointers

我想知道是否有其他方法可以为指针分配指向其值的地址.例如,通常的方法是:

int a = 10;
int *ptr;
ptr = &a;
Run Code Online (Sandbox Code Playgroud)

但在某些地方,我看到它宣称:

int *ptr = &a;
Run Code Online (Sandbox Code Playgroud)

这两种方式都是等价的吗?我有点困惑,因为我一直认为*ptr给出a的,而不是地址.有人可以解释一下吗?谢谢.

art*_*rtm 9

我有点困惑,因为我一直认为*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)
  • 1)作为指针的*手段(但它尚未指向任何有效位置).ptrint
  • 在2)的*该装置ptr是一个指向int,并且其初始值是可变的地址a.
  • 在3)中*是取消引用运算符,即指定ptr变量值指向的内容b.