扩展结构数组

时间:2012-03-13 21:43:21

标签: c struct realloc

这是扩展结构数组的正确方法吗?

typedef struct { int x,y,z;} student_record;

int main(){

student_record data_record[30];       // create array of 30 student_records
num_of_new_records = 5;

data_record = realloc(data_record,(sizeof(data_record) + (sizeof(student_record)*num_of_new_records)));

// do I now have an array of 35 student_records???

3 个答案:

答案 0 :(得分:4)

否 - 您无法分配给数组。你的代码甚至不会编译 - 你试过吗?

如果您想realloc(),则需要使用malloc()(或其中一位亲戚):

student_record *data_record = malloc(sizeof(student_record) * 30);

您可能不应该将realloc()的返回值分配回原始变量。如果由于某种原因失败,你将丢失原始指针并泄漏该内存。

答案 1 :(得分:1)

您应该遵循calloc的初始大小模式,然后在必要时使用realloc。重新分配的安全实践需要包括将返回的初始值赋值给临时变量,并在验证没有错误后覆盖第一个值。像这样:

 student_record *data_record = malloc(sizeof(student_record) * 30);
 student_record *tmp;

 // need larger size
 if ((tmp = realloc(data_record, new_size)) == NULL)
    perror(); //possibly exit as well since you're out of memory
 else
   data_record = tmp;

答案 2 :(得分:1)

您只能对堆上的对象使用realloc(动态分配),因此您必须首先使用malloc。

typedef struct { int x,y,z;} student_record;

int main()  
{
    student_record *data_record = malloc(sizeof(student_record)*30);
    assert(data_rocord);
    data_record = realloc(data_record, sizeof(student_record)*35);
    assert(data_record);
    free(data_record);
    exit(EXIT_SUCCESS);

}