结构..任何人都可以解决这个问题吗?

Structure..can anyone figure this out?

为什么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;
    }

因为你将s2的内容复制到p指向的结构中,然后你更新了s2的内容。

Why does p->p1 produce 1, ....?

因为代码上次分配 p->p1 的值是 1 和 ****

//              v--- p1 member
struct S2 s2 = {1,2,3,0};
struct S2 *p;
p = (struct s2 *)malloc(sizeof(struct S2));
*p = s2;  // ****  This copies the contents of `s2` to `*p`.

Why does ... s2.p1 produces 0?

因为代码后来

将0赋值给s2.p1
//              v--- p1 member
struct S2 s2 = {1,2,3,0};
...
s2.p1 = 0;

They (p->p1, s2.p1) both point to the exact same thing

不,他们没有。 p 是一个从分配的内存中赋值的指针,s2 是一个用 struct S2 s2 定义的对象。分配的内存和对象 s2 不是同一个位置。 s2 作为一个结构,从不指向任何东西。