I'm trying to implement a dynamic array of strings. However I encountered a slight problem. I don't allocate the memory properly, but I have no idea what am doing wrong.
My structure for the dynamic array looks like:
typedef struct Array {
char **ids;
int size;
} dynamicArray;
I initialize it with:
void initArray(dynamicArray *array) {
array = malloc(sizeof(dynamicArray));
array->ids = NULL;
array->size = 0;
}
Deallocate by:
void freeArray(dynamicArray *array) {
if (array->size != 0) {
for (int i = 0; i < array->size; i++) {
free(array->ids[i]);
}
array->size = 0;
array->ids = NULL;
}
}
But now the real problem for me is inserting:
void insertArray(dynamicArray *array, char *name) {
if (array == NULL) {
return;
}
int length = strlen(name) + 1;
array = realloc(array, (??));
strcpy(array->ids[array->size++], name);
}
The program fails on the reallocation with: Exception has occurred.. I'm really not sure, what am I doing wrong. I know I should be also allocating the array of string, but have no idea how to put it in there. Could you guys please send me any hints??
initArray()is not returning the pointer to its caller.initArray().initArray()is supposed to allocate thedynamicArraystructure, see stackoverflow.com/questions/13431108/…. If you're calling it with the address of an existing struct, then it shouldn't callmalloc().dynamicArray array;followed byinitArray(&array);dynamicArray array;? Then you don't need to callmalloc(), the memory is already in the variable.