c - 指针指向的值没有更新

标签 c pointers struct

为什么这里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/

相关文章:

c - c编程中使用openssl使用文件IO进行三重DES加密解密

C 内存地址 - 代码有什么问题?

c - 大小为 1 的数组与指向结构的指针

c - `struct point makepoint(int,int)`是什么意思?

c - 杀死一个 fork 的 child

c - 如何在没有中间副本的情况下在标准 C 中实现 memmove?

c - 指针和堆栈实现的问题

c# - 为什么在创建和返回新结构时出现此错误?

c - 如何使用新的 C99 语法初始化结构?

Citrix Virtual Channel SDK - 如何将字符串值从 ICA 客户端返回到服务器?