【问题标题】:double pointer in struct结构中的双指针
【发布时间】:2013-10-14 18:14:09
【问题描述】:

我有一个这样的结构

struct Example
{
    int a;
    int ** b;
}

我想以这样的方式调用 malloc,这样我就可以拥有 b[][],一个双整数数组。 在我的 main 中以 example 名称声明结构后,我这样做了

*example.b = malloc(x);
example.b = malloc(y);

其中 x 和 y 被定义并分配无符号整数。

这样做会给我带来段错误。 如何从这样的双指针中得到一个双数组?

【问题讨论】:

    标签: c arrays pointers malloc dynamic-allocation


    【解决方案1】:

    要分配与int[nrows][ncols] 对应的内存,您可以执行以下操作:

    int i, nrows, ncols;
    struct Example str;
    
    str.b = malloc(nrows * sizeof(*(str.b)));
    if (str.b==NULL)
        printf("Error: memory allocation failed\n");
    
    for (i=0; i<nrows; ++i) {
        str.b[i] = malloc(ncols * sizeof(*(str.b[i])));
        if (str.b[i]==NULL)
            printf("Error: memory allocation failed\n");
    }
    

    【讨论】:

      【解决方案2】:

      首先你想要x指针的内存,然后你想要每个指针指向足够大的内存块来保存y整数:

      int i = 0;
      example.b = malloc(x * sizeof(int*));
      for (i = 0; i < x; ++i)
          example.b[i] = malloc(y * sizeof(int));
      

      不要忘记,对于每个 malloc,必须调用 free 来释放此内存:

      for (i = 0; i < x; ++i)
          free(example.b[i]);
      free(example.b);       
      

      【讨论】:

      • 为什么我需要 malloc 第一维的每个元素?我最近尝试交换我的代码,以便执行 example.b = malloc(x); *example.b = malloc(y);这可以正常工作,并且以相同的顺序释放也可以。
      猜你喜欢
      • 2020-11-15
      • 1970-01-01
      • 1970-01-01
      • 2011-11-30
      • 2014-06-15
      • 2021-12-16
      • 2022-01-06
      • 1970-01-01
      • 2017-08-24
      相关资源
      最近更新 更多