【发布时间】:2017-10-30 03:58:30
【问题描述】:
我无法弄清楚如何从传递给函数的嵌套结构中获取值。我正在尝试以下方法:
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 }
我一直在寻找有关 malloc'ing 内存的说明,即使它已经定义了?考虑到嵌套的结构和指针,取消引用也有点令人困惑。
【问题讨论】:
-
你为什么在
calcSize()里面做一个malloc? -
@John3136 我试图按照给出的示例进行操作。指针A不需要分配空间吗?
-
为什么要使用双指针?函数中的 malloc 覆盖 main 中的 malloc 并导致泄漏以及未初始化数据的使用。
-
对于未来的问题,请研究minimal reproducible example 的概念。行号(虽然是个好主意)破坏了 C 语法。请给他们,但让他们成为cmets。例如。
/* 13 */而不是13。
标签: c pointers struct structure pass-by-reference