Chef Flambe
Chef Flambe

Reputation: 885

Extending a Structure Array

Would this be the proper way to extend a structure array?

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???

Upvotes: 1

Views: 378

Answers (3)

Tomas Pruzina
Tomas Pruzina

Reputation: 8877

You can only use realloc on objects that are on heap (dynamically allocated) thus you have to malloc first.

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);

}

Upvotes: 1

dbeer
dbeer

Reputation: 7203

You should follow the pattern of calloc'ing the initial size and then using realloc when necessary. Safe practice for realloc'ing need to include assigning the initial value returned to a temporary variable and over-writing the first after verifying that there are no errors. Something like this:

 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;

Upvotes: 1

Carl Norum
Carl Norum

Reputation: 224864

No - you can't assign to an array. Your code won't even compile - did you try it?

If you want to realloc() you need to have used malloc() (or one of its relatives):

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

You probably shouldn't be assigning the return value of realloc() back to the original variable, either. If it fails for some reason, you'll lose the original pointer and leak that memory.

Upvotes: 4

Related Questions