【发布时间】:2018-05-30 19:11:17
【问题描述】:
为什么 p->p1 产生 1,而 s2.p1 产生 0?它们都指向完全相同的东西,而 p->p2 和 s2.p2 不会发生这种情况。
#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,0};
struct S2 *p;
p = (struct s2 *)malloc(sizeof(struct S2));
*p = s2;
s2.p1 = 0;
printf("p->p1 %d,s2.p1 %d \n\n",p->p1, s2.p1 );
printf("%d\t %d\t %d\t %d\t %d\n",p->p1 , s2.p1 , p->p2 , p->s1.p2 );
s = p->p1 + s2.p1 + p->p2 + p->s1.p2;
free(p);
printf("%d", s);
return 0;
}
【问题讨论】:
-
@WeatherVane 这是错误的。看到问题了吗?
p = (struct s2 *)malloc(sizeof(struct S2)); -
无论如何,
p->p1与s2.p1不同。p获取s2内容的副本,但不指向s2。 -
test.c(17):警告 C4133:'=':不兼容的类型 - 从 's2 *' 到 'S2 *'。 test.c(24): 警告 C4473: 'printf' : 没有为格式字符串传递足够的参数。 test.c(24):注意:占位符及其参数需要 5 个可变参数,但提供了 4 个。 test.c(24):注意:格式字符串 '%d' 需要缺少的可变参数 5。
-
.code.tio.c:17:7: warning: assignment to ‘struct S2 *’ from incompatible pointer type ‘struct s2 *’.code.tio.c:24:34: warning: format ‘%d’ expects a matching ‘int’ argument -
旁白:谁或什么文字建议
(struct s2 *)p = (struct s2 *)malloc(sizeof(struct S2));中的演员?