指针问题和困惑

Tho*_*mas 1 c null pointers

这可能很简单,但让我感到困惑.

int x;
int *p = NULL;
int *q = &x;
Run Code Online (Sandbox Code Playgroud)

什么时候会发生

 q = p;   // Address where q points to equals NULL  .
 &x = q;  // I don't think this is possible  .
 *q = 7;  // Value of memory where q is pointing to is 7?  
 *q = &x  // That's just placing the address of x into memory where q points to right?  
 x = NULL;
Run Code Online (Sandbox Code Playgroud)

Pet*_*der 5

q = p;

是.q现在指向NULL,就像p.

&x = q;

不合法.您无法重新分配变量的地址.

*q = 7;

是,设置q指向的地址的内存7.如果q指向NULL那么这将导致错误.

*q = &x;

不合法,q指向一个整数,因此您无法为其分配地址.这是合法的,因为存在从int*(&x)到int(*q)的隐式转换,但不是很安全.在C++中,它只是一个普通的错误.你是对的说它把x(施放到int)的地址放入指向的内存中q.