[英]*a++ = *b++ (what does it mean, how it works)
What would be the values after performing this operation?执行此操作后的值是多少?
#include <stdio.h>
int main() {
int *a = 0;
int *b = 3;
*a++ = *b++;
printf("%d", a);
printf("%d", b);
return 0;
}
The code above gives me a segmentation fault.上面的代码给了我一个分段错误。
*a++ = *b++
(what does it mean, how it works)*a++ = *b++
(这是什么意思,它是如何工作的)
*a++ = *b++;
means方法
*(a++) = *(b++);
x++
increments x
and returns the original value. x++
递增x
并返回原始值。 So the following is equivalent:所以下面是等价的:
*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`.
Before: After:
a a
+----------+ +----------+ +----------+ +----------+
| ---------->| x | | ------+ | p |
+----------+ +----------+ +----------+ | +----------+
| y | +--->| y |
+----------+ +----------+
| | | |
b b
+----------+ +----------+ +----------+ +----------+
| ---------->| p | | ------+ | p |
+----------+ +----------+ +----------+ | +----------+
| q | +--->| q |
+----------+ +----------+
| | | |
The code above gives me a segmentation fault.上面的代码给了我一个分段错误。
You assigned garbage to a
and b
.您将垃圾分配给a
和b
。 0
as a pointer is the NULL pointer, and 3
isn't a valid pointer. 0
作为指针是 NULL 指针,而3
不是有效指针。
Given鉴于
#include <stdio.h>
int main() {
int *a = 0;
int *b = 3;
*a++ = *b++;
printf("%d", a);
printf("%d", b);
return 0;
}
the printed values can not be predicted as the code invokes undefined behavior in multiple ways.由于代码以多种方式调用未定义的行为,因此无法预测打印的值。
First, both *a
and *b
invoke undefined behavior by dereferencing invalid pointers - a
is initialized to a null pointer value, and b
is initialized to point to address 3
, which is almost certainly invalid also.首先, *a
和*b
都通过取消引用无效指针来调用未定义的行为 - a
被初始化为 null 指针值,而b
被初始化为指向地址3
,这几乎肯定也是无效的。
Second, printf("%d", a);
二、 printf("%d", a);
invokes undefined behavior by trying to print an int *
variable with the %d
format specifier for int
.通过尝试使用 int 的%d
格式说明符打印int
int *
变量来调用未定义的行为。 The proper code would be正确的代码是
printf("%p", ( void * ) a);
It's not clear what the currently-posted code is supposed to do.目前尚不清楚当前发布的代码应该做什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.