I am working with dynamic arrays, consider two scenarios - Scenario 1:
typedef struct
{
int *array;
int dataPtr;
} A;
static A dynaArray;
//Call the function as
dynaAdd(&dynaArray, <pointer to data block>, <length> );
static bool dynaAdd(A *data, int *dataCopy, int len)
{
int newlen = (data->dataPtr + len);
data->array = (int *) realloc(data->array, newlen * sizeof(int));
if (!data->array)
{
return FALSE;
}
memcpy(&data->array[data->dataPtr], dataCopy, len* sizeof(int));
data->dataPtr += len; // update data ptr
return TRUE;
}
I create a static struct A data (say) and pass to a function as pointer which reallocates length for A->array everytime and adds data to it, maintaining a dataPtr for index. This works perfectly fine where I can create an A->array of say length 100, use the data and free the pointer and null.
On the other scenario 2 -
static int *dynArray;
//Call the function as
dynaAdd(dynaArray, <pointer to data block>, <len>, <dataIdx> );
static bool dynaAdd(int *data, int *dataCopy, int len, int dataIdx)
{
int newlen = (dataIdx + len);
data = (int *) realloc(data, newlen * sizeof(int));
if (!data)
{
return FALSE;
}
memcpy(&data[dataIdx], dataCopy, len* sizeof(int));
dataIdx += len ;
return TRUE;
}
I just use int *array instead of struct, maintaining a static int dataPtr(say) to keep track of the next index, pass the array pointer to the function and dynamically grow the array and add contents to it. However, the program crashes after creating some x length array (which keeps varying).
Can someone help understand the difference between the two approaches ? In both scenarios, the goal is to create a dynamic array and keep adding contents to it until the certain data index and then free the array.
Thank you.