如何动态将内存分配给结构内的指针数组

时间:2018-11-21 07:33:43

标签: c data-structures dynamic-memory-allocation

这是我到目前为止所做的事情

struct test_case {
  int n;
  int *test[];
};


struct test_case *test_case_struct = (struct test_case *)malloc(
      sizeof(struct test_struct) + 100 * sizeof(int));

我需要在“测试”指针数组中分配n个指针。据我所知,我需要为结构分配空间,然后为指针数组分配更多空间,但是当我尝试对此进行编译时,出现错误 无效使用sizeof运算符以不完整类型struct test_struct

如果有人可以告诉我,我如何将 n的值用作用户输入,并使 int *测试[n] 成为可能。

3 个答案:

答案 0 :(得分:0)

当前您正在使用灵活数组(又名零长度数组)。 可以如下分配。

struct test_case *test_case_struct =
   malloc(sizeof (*test_case_struct) + 100 * sizeof (int *));

请注意,代码中*和错字字int缺少sizeof(struct test_struct)


或者,您可以使用如下所示的指向指针的指针。

struct test_case {
  int n;
  int **test;
};


struct test_case *test_case_struct = malloc(
      sizeof(*test_case_struct));
test_case_struct->test = malloc(100 * sizeof(int *)); // Allocates 100 pointers

答案 1 :(得分:0)

您需要更改

  sizeof(struct test_struct)

   sizeof(struct test_case)

因为test_struct不是正确的结构类型。

以更好的方式,您还可以使用已声明的变量名称,例如

struct test_case *test_case_struct = malloc(
         sizeof (*test_case_struct) + n * sizeof(int*));

也就是说,您需要为弹性成员分配int *而不是int的内存。

此外,下面是一个片段,该片段显示了该计数被视为用户输入

int main(void)
{
    int n = 0;
    puts("Enter the count of pointers");
    if (scanf("%d", &n) != 1) {
        puts("Got a problem in the input");
        exit (-1);
    }
    struct test_case *test_case_struct = malloc( sizeof(struct test_case) + n * sizeof(int*));
    printf("Hello, world!\n");
    return 0;
}

答案 2 :(得分:0)

不重复类型名称。您已经偶然发现了自己的代码两次,因为这样做了。您输入了错误的struct标签,并使int*的{​​{1}}感到困惑。

更艰苦的分配看起来像这样

int

这里将分配struct test_case *test_case_struct = malloc(sizeof (*test_case_struct) + sizeof (test_case_struct->test[0]) * 100); 所指向的大小,再加上test_case_struct应具有的100个大小。现在,您可以使用结构定义,而无需中断对malloc的调用。而且,如果您确实进行了重大更改(例如重命名test_case_struct->test[0]),编译器会立即通知您。

相关问题