c - 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 也应该改变了。
我哪里错了?
解决方案
p
不是指向s2
所以更改对s2
没有影响p
。
p
指向由 . 返回的内存malloc
。该内存已通过复制s2
here的内容来填充*p = s2
,但这并不意味着(那将是)。p
s2
p = &s2
如果您正确理解 和 之间的区别*p = s2
,p = &s2
那么您将在理解指针方面走得更远。
推荐阅读
- php - How can I display elements of my ArrayCollection working with joined Tables and ManyToMany relations?
- css - How to make table headers non scrollable bootstrap vue
- javascript - .getAttribute is not a function
- scala - 如何随机采样 DataFrame 中的一小部分行?
- python - Networkx - How can i get value from "all_pairs_shortest_path_length" function?
- android - Getting UUID of nearby beacon
- erlang - 如何在 EUnit 测试用例中禁用错误记录器?
- javascript - SyntaxError:位置 2 的 JSON 中的意外标记 <
- c# - BackgroundWorker RunWorkerCompleted 未在 UI 线程上执行
- r - how to use case_when rather then if_else [Error in my code?]