【问题标题】:Nested Structures and Dereferencing Pointers in CC中的嵌套结构和取消引用指针
【发布时间】: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


【解决方案1】:

几件事:

1) 您有内存泄漏,因为*A = malloc(sizeof(struct rect)); 重新分配了先前在main 而不是freed 中分配的指针。

2) 不要在 C 中强制转换 malloc 的返回值。Do I cast the result of malloc?

【讨论】:

  • 3) 为什么要使用双指针? 4) A 指向未初始化的数据,因此 test = (*A)->ne.x; 是未定义的行为。
猜你喜欢
  • 2023-04-07
  • 2012-09-23
  • 2011-02-04
  • 2013-01-04
  • 2020-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-14
相关资源
最近更新 更多