Hi,
When i use realloc to re-size my array it is re-sizing it correctly but my some of my data is getting lost.
Strange thing is that If I don't use realloc, I can still re-size my array by just increasing the index before inserting the data. In this case my data doesn't get lost.
-------------------creating dynamic array--------------

int size = 1;
 float *store_x_postions = NULL;
 store_x_postions = (float*) malloc(size * sizeof(float));
 store_x_postions[0] = 0;

-----------------inserting data--------------------

store_x_postions[ size] = random_x_pos;
size++;

----------code using realloc-------------------

float *temp = (float*) realloc (store_x_postions, (size+1) * sizeof(float));
if(temp != NULL){
store_x_postions = temp;
}

----------------------Output in terminal if I use realloc-------------------------------------
x in store_x_postions : 0.000000 at index 0
x in store_x_postions : 0.000000 at index 1 // this should be 101.000000
x in store_x_postions : 525.000000 at index 2
x in store_x_postions : 559.000000 at index 3
x in store_x_postions : 465.000000 at index 4
x in store_x_postions : 146.000000 at index 5
------------------------Output in termial if I don't use realloc--------------------
x in store_x_postions : 0.000000 at index 0
x in store_x_postions : 101.000000 at index 1
x in store_x_postions : 525.000000 at index 2
x in store_x_postions : 559.000000 at index 3
x in store_x_postions : 465.000000 at index 4
x in store_x_postions : 146.000000 at index 5
---------------------------------------------------------------------
Only difference in the two codes is that I turn the realloc bit into comments.
Anyone know why this is happening, thanks

>>store_x_postions[ size] = random_x_pos;

Above is incorrect -- must be (size-1) so that when size == 1 then the correct index value is 0, not 1.

Thanks, that has solved the problem.

Do you know I can still re-size the array without using realloc though?

Thanks


Do you know I can still re-size the array without using realloc though?

Thanks

Yes you can, but you'd have to just duplicate the realloc() function. All it does is allocate a new pointer of the desired size, copy the data from old to new pointer, then finally free() the old pointer.

This question has already been answered. Start a new discussion instead.