【发布时间】:2018-08-05 19:45:02
【问题描述】:
我遇到了一个实例,其中内存被动态分配给结构内的 char 指针,这种方式对我来说没有多大意义,但 - 当然 - 有效。 similar question 之前已经发布过。然而,答案并没有帮助我理解分配过程中实际发生的事情。
这是我找到的代码示例:
struct a_structure {
char *str;
struct a_structure *next;
};
内存已按以下方式分配:
ptr_start=(struct a_structure *)malloc(sizeof (struct a_structure *));
...
char *some_words="How does this work?";
ptr_start->str=(char *)malloc(strlen(some_words)+1);
strcpy(ptr_start->str, some_words);
ptr_start->next=(struct a_structure *)malloc(sizeof(struct a_structure *));
...
我不明白为什么malloc 在这里与指针的大小一起使用。 ptr_start 是 struct a_structure 类型的指针。这意味着它需要大小为sizeof(struct a_structure) 的内存+ 未在结构声明中指定的我的字符串的大小。然而,在上面的例子中,malloc 返回另一个指向a_structure 类型结构的指针的地址,对吗?
【问题讨论】:
-
“我不明白为什么 malloc 在这里与指针大小一起使用” - 我明白。意思是作者写错了。可能是因为他们不经常写惯用的 C。
-
我不明白为什么 malloc 在这里与指针大小一起使用。 ptr_start:我也没有,可能是错的,应该是
sizeof (struct a_structure)。您在哪里找到该代码? -
顺便说一句,如果您阅读this Q&A,您将学习如何避免此类错误等等。
-
我在 Jürgen Wolf 的一本名为“C von A bis Z”(德语)的关于 C 编程语言的书中发现了这一点。
-
我猜作者不知道字母表。它是:B、BCPL、C、C++、D、Java、J++、C#。
标签: c pointers struct dynamic-memory-allocation