ptr =&a和*ptr = a是否相同?

mko*_*mko 0 c pointers

在书中它解释说:

ptr = &a /* set ptr to point to a */

*ptr = a /* '*' on left:set what ptr points to */
Run Code Online (Sandbox Code Playgroud)

它们对我来说似乎是一样的,不是吗?

Oli*_*rth 7

不会.第一个更改指针(现在指向a).第二个改变了指针所指向的东西.

考虑:

int a = 5;
int b = 6;

int *ptr = &b;

if (first_version) {
    ptr = &a;
    // The value of a and b haven't changed.
    // ptr now points at a instead of b
}
else {
    *ptr = a;
    // The value of b is now 5
    // ptr still points at b
}
Run Code Online (Sandbox Code Playgroud)