c - C 中的嵌套结构和取消引用指针

标签 c pointers struct structure pass-by-reference

我无法弄清楚如何从传递给函数的嵌套结构中获取值。我正在尝试以下操作:

 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/

相关文章:

c - 反转字符串的库函数

c++ - 如何实现 observer_ptr?

c - 如何在不使用通用指针的情况下引用指向数据或数据的指针?

c - 在 C 中使用 atoi() 时出现运行时错误

c - 如何保护解释器的 native 调用堆栈免受垃圾收集?

c - build 一台扫描仪。识别代币

c - 说一个指针等于C中内存中的一个位置

C题: error: expected ')' before '*' token

c - C 中的链表和结构 - 在函数中将链表和结构作为参数传递(C)

c - 将字符串分成更小的部分并组织结构(C 编程)