【问题标题】:How do I dynamically allocate memory to a pointer array inside a structure如何动态地将内存分配给结构内的指针数组
【发布时间】:2019-04-23 17:39:49
【问题描述】:

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

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 个指针。据我所知,我需要为结构分配空间,然后为指针数组分配更多空间,但是当我尝试编译它时,我得到了错误 对不完整类型的 struct test_struct 无效使用 sizeof 运算符

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

【问题讨论】:

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


【解决方案1】:

不要重复类型名称。您已经两次偶然发现自己的代码,因为您这样做了。您输入了错误的结构标记并将int*int 混淆。

更严格的分配看起来像这样

struct test_case *test_case_struct =
  malloc(sizeof (*test_case_struct) + sizeof (test_case_struct->test[0]) * 100);

这里将分配test_case_struct 指向的任何大小,加上test_case_struct->test[0] 应该是100 多个。现在您可以在不中断对 malloc 的调用的情况下使用结构定义。如果您确实执行了重大更改(例如重命名 test),编译器会立即通知您。

【讨论】:

    【解决方案2】:

    你需要改变

      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 *s 的内存,而不是 ints。

    另外,下面是一个 sn-p,它显示计数被视为用户输入

    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;
    }
    

    【讨论】:

    • 我的意图是有一个可以指向 n 元素的指针数组。其中 n 是用户输入。 n 和指针数组都在结构内。抱歉,sn-p 中的拼写错误
    • @ShivaKumar 所以,你是说,你不需要指向ints 的指针数组,而是ints 的数组,ints 的计数是存储在n,对吧?
    • 不。如果我有一个指针数组 int *test[n], n 将是一个用户输入(这对我来说并不具有挑战性,我以前做过),复杂性是我需要把指针数组放在哪里 int *test[ ] 在结构中,以及它在结构中的大小 int n。我需要的用例是我让用户输入不同维度的不同方阵(int n)。 test[0], test[1] ... test[n] 中的每个指针都指向一个 int 数组,而该数组又具有 n 里面的元素。我希望我已经把图片说得够清楚了。
    【解决方案3】:

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

    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
    

    【讨论】:

    • 又为什么不适合柔性阵列?
    • @SouravGhosh 我只是ass*u*me*d OP 可能不打算使用灵活的数组并意外声明了这样的结构。
    • @kiranBiradar 标题表明结构中需要一个指针数组。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-04-15
    • 2013-04-18
    • 2019-10-20
    • 1970-01-01
    • 1970-01-01
    • 2012-07-10
    • 2013-10-04
    相关资源
    最近更新 更多