我正在尝试向已经使用固定大小20进行了malloc的结构体中添加10个元素。这是我定义结构体的方式:
#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;
}
我原本想通过realloc重新分配内存(不过,我不确定如何实现):
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";
我该如何实现这个?非常感谢您的帮助!
struct st_temp * temp = malloc( 20 * sizeof *temp ); for (...) { temp[i].prod = "foo"; }
?手动管理的内存越少,解决方案就越不易出错。 - David Rodríguez - dribeas