*a++ = *b++(这是什么意思,它是如何工作的)

Yel*_*907 -2 c pointers post-increment

执行此操作后,值会是多少?

#include <stdio.h>
int main() {
    int *a = 0;
    int *b = 3;
    *a++ = *b++;
    printf("%d", a);
    printf("%d", b);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

上面的代码给了我一个分段错误。

ike*_*ami 5

*a++ = *b++(这是什么意思,它是如何工作的)

*a++ = *b++;
Run Code Online (Sandbox Code Playgroud)

方法

*(a++) = *(b++);
Run Code Online (Sandbox Code Playgroud)

x++递增x并返回原始值。所以以下是等价的:

*a = *b;     // Copy the `int` to which `b` points into the `int` to which `a` points.
a = a + 1;   // Make `a` point to the following `int`.
b = b + 1;   // Make `b` point to the following `int`.
Run Code Online (Sandbox Code Playgroud)
Before:                                     After:

a                                           a
+----------+        +----------+            +----------+        +----------+
|        ---------->| x        |            |        ------+    | p        |
+----------+        +----------+            +----------+   |    +----------+
                    | y        |                           +--->| y        |
                    +----------+                                +----------+
                    |          |                                |          |


b                                           b
+----------+        +----------+            +----------+        +----------+
|        ---------->| p        |            |        ------+    | p        |
+----------+        +----------+            +----------+   |    +----------+
                    | q        |                           +--->| q        |
                    +----------+                                +----------+
                    |          |                                |          |
Run Code Online (Sandbox Code Playgroud)

上面的代码给了我一个分段错误。

您将垃圾分配给ab0因为指针是 NULL 指针,并且3不是有效的指针。