c - malloc 结构指针数组与结构数组

标签 c arrays pointers struct malloc

有什么区别

struct mystruct *ptr = (struct test *)malloc(n*sizeof(struct test));

struct mystruct **ptr = (struct test *)malloc(n*sizeof(struct test *));

它们都工作得很好,我只是想知道两者之间的实际区别。第一个是否分配一个结构数组,而第二个分配一个结构指针数组?另一种方式?另外,哪个占用的内存更小?

最佳答案

第一个分配一个struct数组,另一个分配一个指向struct的指针数组。在第一种情况下,您可以通过立即分配 ptr[0].field1 = value; 来写入字段,而在第二种情况下,您必须先分配 struct 本身进行实际写作。

在 C 中删除 malloc 结果的转换是可以的,所以你可以这样写

struct mystruct **ptr = malloc(n*sizeof(struct test *));
for (int i = 0; i != n ; i++) {
    ptr[i] = malloc(sizeof(struct test));
}
ptr[0]->field1 = value;
...
// Do not forget to free the memory when you are done:
for (int i = 0; i != n ; i++) {
    free(ptr[i]);
}
free(ptr);

关于c - malloc 结构指针数组与结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12334343/

相关文章:

c - 尝试水平翻转图像

c - 通过C函数返回指向数组的指针

c# - 在 C# 中使用 System.IO.File.ReadAllLines(fil) 跳过第一行

javascript - jquery数组按多个元素分组并查找总数

c - 使用指针交换

c++ - 如何使用智能指针进行自动清理?

c - LEAL 汇编指令有什么作用?

c - 将指针数组设置为 NULL 的标准方法是什么?

在 C 中使用 <<(less less)创建 char 数组

c++ - 数组声明在 C++ 中如何工作?