简体   繁体   English

C 中的嵌套结构和解除引用指针

[英]Nested Structures and Dereferencing Pointers in C

I am having trouble figuring out how to get a value from a nested structure that is being passed into a function.我无法弄清楚如何从传递给函数的嵌套结构中获取值。 I am trying the following:我正在尝试以下操作:

 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 }

I was looking for clarification regarding malloc'ing memory for this even though it's already defined?我一直在寻找关于 malloc'ing memory 的澄清,即使它已经定义? And also the dereferencing is a bit confusing given the nested structs and pointer.考虑到嵌套的结构和指针,取消引用也有点令人困惑。

Couple of things:几件事:

1) You have a memory leak because *A = malloc(sizeof(struct rect)); 1) 你有内存泄漏,因为*A = malloc(sizeof(struct rect)); reassigns the pointer which was previously allocated in main and not free d.重新分配之前在main分配的指针而不是free d。

2) Don't cast the return value of malloc in C. Do I cast the result of malloc? 2) 不要在 C 中转换 malloc 的返回值。 我是否转换了 malloc 的结果?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM