首页 > 解决方案 > cProgramming:误解引用指向 int 结构和嵌套结构(也是 int)的元素的指针

问题描述

这是 cppinstitute 的 CLA 考试的样题

问题是以下代码的输出是什么?正确答案是“8”,我得到的正是这个结果,但我不明白为什么。

#include <stdio.h>
#include <stdlib.h>
//struct of two ints
struct S1 {
    int p1,p2;
    };

// struct of an int, struct of two ints, and another int
struct S2 {
    int p1;
    struct S1 s1;
    int p2;
    };

int main(void) {
  // set an int to 0
    int s = 0;
  // invoke a struct type 2 and fill with 1, 2, 3, 4
  // like: 
  // struct S2 {
  // int p1; // = 1
  // struct S1 s1; // = 2,3
  // int p2; // = 4
  // };
    struct S2 s2 = { 1, 2, 3, 4 };
  // prepare a pointer of same type like the struct above
    struct S2 *p;
  // claim memory for the pointer
    p = (struct S2 *)malloc(sizeof(struct S2));
  // point to already filled struct
    *p = s2;
  // the int 1 is replaced with 0
    s2.p1 = 0;
  // s is assembled
  // = 1 + 0 + 4 + 3 = 7
    s = p->p1 + s2.p1 + p->p2 + p->s1.p2; // WHY p->p1 IS 1 AND NOT 0 ???
    free(p);
    printf("%d",s);
    return 0;
}

Aus 我理解它(并在评论中写到让我清楚) p->p1 用指针引用结构的第一个元素。那应该是 0(而不是 1),因为在语句中使用“.”-操作符时,s2.p1 = 0;p1 处的 struct s2 的值应该从 1 更改为 0。所以指向该元素的指针用“-”引用>"-operator 也应该改变了。

我哪里错了?

标签: cpointersstruct

解决方案


p不是指向s2所以更改对s2没有影响p

p指向由 . 返回的内存malloc。该内存已通过复制s2here的内容来填充*p = s2,但这并不意味着(那将是)。ps2p = &s2

如果您正确理解 和 之间的区别*p = s2p = &s2那么您将在理解指针方面走得更远。


推荐阅读