【发布时间】:2011-05-03 04:31:16
【问题描述】:
我正在尝试向我的结构添加 10 个以上的元素,这些元素已经是 malloc 且固定大小为 20。这就是我定义结构的方式:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct st_temp {
char *prod;
};
int main ()
{
struct st_temp **temp_struct;
size_t j;
temp_struct = malloc (sizeof *temp_struct * 20);
for (j = 0; j < 20; j++) {
temp_struct[j] = malloc (sizeof *temp_struct[j]);
temp_struct[j]->prod = "foo";
}
return 0;
}
所以我的想法是重新分配为(但是,不确定如何):
temp_struct = (struct st_temp **) realloc (st_temp, 10 * sizeof(struct st_temp*));
然后添加额外的 10 个元素,
for (j = 0; j < 10; j++)
temp_struct[j]->prod = "some extra values";
我怎样才能做到这一点?任何帮助表示赞赏!
【问题讨论】:
-
我同意 Daniel... 双指针间接寻址的原因是什么?拥有
struct st_temp * temp = malloc( 20 * sizeof *temp ); for (...) { temp[i].prod = "foo"; }不是更简单吗?您手动管理的内存越少,解决方案就越不容易出错。