realloc structure with function in C

后端 未结 3 760
栀梦
栀梦 2021-01-27 07:22

My C program is crashing and I am too new to figure it out. It\'s very simple so far and I imagine the code is enough to figure out what is going wrong.

I am simply try

相关标签:
3条回答
  • 2021-01-27 07:50

    Realloc reallocates memory, so probably memory pointed by d will be released, so double_array_size has to edit d, you could try:

    void double_array_size(struct course** d, int new_size){
    *d = realloc(*d, new_size * sizeof(struct course));
    .
    .
    .
    }
    
    0 讨论(0)
  • 2021-01-27 07:59

    Combining Ingo's and codroipo's answers, you have to either return the new pointer from double_array_size, or you have to pass in a pointer to d so you can update the pointer from double_array_size

    0 讨论(0)
  • 2021-01-27 08:02

    realloc() may return a different pointer than the original one but you assign that to temp only so the calling function still works with the original pointer afterwards. Change double_array_size() to return the new pointer returned by realloc() and call

    d = double_array_size(d, array_size);
    

    Furthermore you should always check the result fo malloc(), realloc() etc. They may return NULL if there is no more memory available

    0 讨论(0)
提交回复
热议问题