为什么这里p->p1是1而不是0?我以为p是指向struct s2的指针,并且s2.p1=0,所以p->p1也应该是0?
#include <stdio.h>
#include <stdlib.h>
struct S1 {
int p1,p2;
};
struct S2 {
int p1;
struct S1 s1;
int p2;
};
int main(void) {
int s=0;
struct S2 s2 = {1, 2, 3, 4};
struct S2 *p;
p=(struct S2 *)malloc(sizeof(struct S2));
*p = s2;
s2.p1 = 0;
s=p->p1 + s2.p1 + p->p2 + p->s1.p2;
free(p);
printf("%d", s);
return 0;
}
我预期输出为 7,但实际输出为 8。
最佳答案
p
实际上并不指向 s2
!。您已将 s2
复制到 p
分配的地址中。如果您希望 p
指向 s2
,请不要对其进行 malloc
。相反,只需说struct S2 *p = &s2;
。
关于c - 指针指向的值没有更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57397891/