小编Jos*_*osh的帖子

如何为我的C结构数组分配更多空间?

我正在尝试向我的结构添加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;
}
Run Code Online (Sandbox Code Playgroud)

所以我想到的是重新分配(但是,不知道如何):

temp_struct = (struct st_temp **) realloc (st_temp, 10 * sizeof(struct st_temp*));
Run Code Online (Sandbox Code Playgroud)

然后添加额外的10个元素,

   for (j = 0; j < 10; j++)
      temp_struct[j]->prod = "some extra values";
Run Code Online (Sandbox Code Playgroud)

我怎么能实现这个目标?任何帮助表示赞赏!

c malloc struct realloc

5
推荐指数
2
解决办法
9298
查看次数

标签 统计

c ×1

malloc ×1

realloc ×1

struct ×1