我无法弄清楚如何从传递给函数的嵌套结构中获取值。我正在尝试以下操作:
13 int calcSize(struct rect **A) {
14
15 int test;
16
17 *A = malloc(sizeof(struct rect));
18
19 // (*A)->ne.x = (int *)malloc(sizeof(int));
20 test = (*A)->ne.x;
21 printf("%d",test);
22
23 return 0;
24
25 }
26
27
28 int main () {
29
30 int sum;
31
32 struct rect *input;
33 input = (struct rect*)malloc(sizeof(struct rect));
34 input->ne.x = 4;
35 input->ne.y = 6;
36 input->nw.x = 2;
37 input->nw.y = 6;
38 input->se.x = 4;
39 input->se.y = 2;
40 input->sw.x = 2;
41 input->sw.y = 2;
42
43 printf("%d",input->sw.y);
44
45 sum = calcSize(&input);
46
47
48 return 0;
49 }
我正在寻找有关为此分配内存的说明,即使它已经定义了?考虑到嵌套的结构和指针,解除引用也有点令人困惑。
最佳答案
有几件事:
1) 出现内存泄漏,因为 *A = malloc(sizeof(struct rect));
重新分配了之前在 main
中分配的指针,而不是 免费
d.
2) 不要在 C 中转换 malloc 的返回值。Do I cast the result of malloc?
关于c - C 中的嵌套结构和取消引用指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47007955/