繁体   English   中英

如何使用 malloc 和结构指针数组

[英]How work with malloc and array of struct pointer

我想尝试分配我的前 10 个结构。 我们必须在堆中存储一个结构指针数组,但我不知道我在做什么错

我的结构看起来像这样

typedef struct TEST
{
    char* first_string;
    char* second_string;
} test;

我写的是:


test **string_pair;

string_pair = malloc(10 * sizeof(test *));
  if(string:pair == NULL)
  {
    free(string_pair);
    exit(4);
  }

这很好用但是后来我尝试在for循环中分配我的字符串


string_pair[count]->first_string = malloc(10 * sizeof(char)); // note that count is currently 0
  if(string_pair[count]->first_string == NULL)
  {
    free(string_pair[count]->first_string);
    free(string_pair[count]);
    exit(4);
  }

我得到一个分段错误

在任何人建议我们不允许简单地使用结构数组之前,我们必须以复杂的方式来做。

提前谢谢

您分配了一个指针数组。

但是您没有为实际结构分配 memory,也没有初始化分配的指针。

这一行:

string_pair = malloc(10 * sizeof(test *));

分配可以存储 memory 地址的 4 或 8 个(取决于您的架构)字节变量的数组。

它不分配struct TEST 指针将包含垃圾(可能无效)地址,直到您对其进行初始化。

您应该通过为struct TEST调用malloc并将结果指针放入数组中来实现。

否则,当您的代码到达这一行时:

string_pair[count]->first_string

它将在某个随机地址(可能为 0)处查找struct TEST ,并尝试读取其first_string字段,这将导致分段错误。

您遇到了分段错误,因为您分配了一个指针数组,但没有分配结构本身。

使用string_pair = malloc(10 * sizeof(test *)); ,您将string_pair (指向指针的指针)分配给 10 个指针(指向test结构)。

然后,使用string_pair[count]->first_string = malloc(10 * sizeof(char)); ,您将string_pair[count]first_string成员分配给 10 个字符的字符串。 ->标记表示访问string_pair[count]中的成员。 但是,实际结构并未分配。

您需要分配string_pair[count] ,例如string_pair[count] = malloc(sizeof(test)); .

我建议只为您的数组使用test* ,并使用test* string_pair = malloc(10 * sizeof(test));分配它 .

暂无
暂无

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

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