1

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

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

So what method should I use? Create a new temp array of larger size and copy over, then malloc() the first to the size I want and copy back again?
Don't use arrays if you want to use realloc(). Use pointers and malloc().
1

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;

Comments

1

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

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.