简体   繁体   English

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

[英]How do I allocate more space for my array of C structs?

I'm trying to add 10 more elements to my struct that has been already malloc with a fixed sized of 20. This is the way I have my struct defined: 我正在尝试向我的结构添加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;
}

So what I had in mind was to realloc as (however, not sure how to): 所以我想到的是重新分配(但是,不知道如何):

temp_struct = (struct st_temp **) realloc (st_temp, 10 * sizeof(struct st_temp*));

and then add the extra 10 elements, 然后添加额外的10个元素,

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

How could I achieve this? 我怎么能实现这个目标? Any help is appreciated! 任何帮助表示赞赏!

When you use realloc() , you must give the new size instead of the number of bytes to add. 使用realloc() ,必须提供大小而不是要添加的字节数。 So: 所以:

temp_struct = (struct st_temp **) realloc (temp_struct, 30 * sizeof(struct st_temp*));

30 is, of course, your original 20 plus 10 more. 30当然是你原来的20加10多。 The realloc() function takes care of copying the original data to a new location if it needs to move the memory block. 如果需要移动内存块, realloc()函数负责将原始数据复制到新位置。

Then, adding the extra 10 elements would be something like (starting at index 20, not 0): 然后,添加额外的10个元素就像是(从索引20开始,而不是0):

for (j = 20; j < 30; j++) {
    temp_struct[j]->prod = "some extra values"; 
}

To avoid memory leaks, we need to handle reallocating with care (more on that later). 为了避免内存泄漏,我们需要谨慎处理重新分配(稍后会详细介绍)。 The realloc function: realloc函数:

void *realloc(void *ptr, size_t size) , where void *realloc(void *ptr, size_t size) ,where

ptr = the pointer to the original ( malloc 'ed) memory block, and ptr =指向原始( malloc )内存块的指针,和

size = the new size of the memory block (in bytes). size =内存块的新大小(以字节为单位)。

realloc returns the new location of the dynamically allocated memory block (which may have changed) - or NULL if the re-allocation failed! realloc返回动态分配的内存块的新位置(可能已更改) - 如果重新分配失败,则返回NULL! If it returns NULL, the original memory stays unchanged, so you must always use a temporary variable for the return value of realloc . 如果它返回NULL,则原始内存保持不变,因此必须始终使用临时变量作为realloc的返回值。

An example will clarify this a bit (points of interest: realloc syntax is similar to malloc's (no need for extra casts etc.) and, after realloc, you need to produce the same steps for the new objects as you did after malloc): 一个例子将澄清一点(兴趣点:realloc语法类似于malloc的(不需要额外的强制转换等),并且在realloc之后,你需要像在malloc之后那样为新对象生成相同的步骤):

struct st_temp **temp_struct;
temp_struct = malloc(20 * sizeof *temp_struct);
if (temp_struct == NULL) { /* handle failed malloc */ }
for (int i = 0; i < 20; ++i) {
    temp_struct[i] = malloc(sizeof *temp_struct[i]);
    temp_struct[i]->prod = "foo";
}

// We need more space ... remember to use a temporary variable
struct st_temp **tmp;
tmp = realloc(temp_struct, 30 * sizeof *temp_struct);
if (tmp == NULL) { 
    // handle failed realloc, temp_struct is unchanged
} else {
    // everything went ok, update the original pointer (temp_struct)
    temp_struct = tmp; 
}
for (int i = 20; i < 30; ++i) { // notice the indexing, [20..30)
    // NOTICE: the realloc allocated more space for pointers
    // we still need to allocate space for each new object
    temp_struct[i] = malloc(sizeof *temp_struct[i]);
    temp_struct[i]->prod = "bar";
}
// temp_struct now "holds" 30 temp_struct objects
// ...
// and always do remember, in the end
for (int i = 0; i < 30; ++i)
    free(temp_struct[i]);
free(temp_struct);

Do note, that this is not really an array of structs, but more an array of pointers to structs - or even an array of arrays of struct if you wish. 请注意,这不是一个结构数组,而是一个指向结构的指针数组 - 如果你愿意的话,甚至是结构数组的数组。 In the last case, each sub-array would be of length 1 (since we only allocate space for one struct). 在最后一种情况下,每个子数组的长度为1(因为我们只为一个结构分配空间)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM