0
Dynamic array
I tried to implement a dynamic array in c. https://code.sololearn.com/cYDLAg5IhwjN/#c Now I don't know why it doesn't print to the screen. Probably because arr->arr[i]? Is there a way to print the array using the -> operator?
3 Réponses
+ 1
And to add, if malloc() fails you should ideally return from the function or you will dereference a NULL pointer.
This will leak memory if realloc() fails:
arr->arr = realloc(arr->arr, arr->length * sizeof(int));
You should create a temporary variable to hold the return value of realloc() and assign it to your pointer if it successfully reallocated the memory block.
int *tmp_arr = realloc(arr->arr, arr->length * sizeof(int));
if (tmp_arr)
arr->arr = tmp_arr;
+ 1
Robin
I know i can do it with &arr and arr.arr[i].
But I tried to use -> operator.
Now if I don't initialize the pointer with NULL it work.
It's ok if i don't initialize a pointer in situations like this?