在结构数组中分配指针

时间:2014-03-31 05:10:59

标签: c arrays pointers struct allocation

好的,所以问题基本上就像标题一样。无法找到能够得到所有内容的问题,所以我想我会问。

说我想要一个形状如下的

结构数组
typedef struct s_woo{
    char** n;
    char* x;
} t_woo;

所以我相信我应该做

t_woo* woos = malloc(num_woos * sizeof(*woos));

看起来很简单(并且应该阻止人们因为我投射malloc的习惯而对我大吼大叫)。

然后我想初始化每个结构中的东西。

我这么直观地说:

for(i = 0; i < num_woos; i++){

    num_ns = randomint1 / randomint2; //let's say num_ns is big, like 250-ish, average, and changes every round of the loop

    woos[i].n = malloc(num_ns * sizeof(char*));
    woos[i].x = malloc(num_ns * sizeof(char));
    for(j = 0; j < num_ns; j++){
        woos[i].n[j] = malloc(16 * sizeof(char)); // I just want 16 characters per char*
    }
}

这是我在代码中的简化版本。我想知道我写的东西可能出现什么问题 - 就像任何可能的事情一样。我没有特别寻找任何东西,只是上面的一般问题,如内存/堆问题,指针错误等。

遗漏&#34;虚拟内存耗尽&#34;。我的代码错误使用malloc上的包装器函数检查它,所以我非常确定不是它。

1 个答案:

答案 0 :(得分:1)

更好:

 static const size_t woo_n_size = 16; 
  /* To make sure you use 16 everywhere,
   * also easier to change it
   */

 struct woo_item {
     char n[woo_n_size];
     char x;
 };

 struct s_woo {
     struct woo_item *items;
     size_t size; / * optinal, to keep track of item count */ 
 }

使用woo_item结构,您可以确保没有分配x的{​​{1}},反之亦然。 您可以通过指定null元素来关闭每个列表来记住woo_items的数量,或者只是将n[woo_n_size]成员存储在size

相关问题