I want to create an array of variable size that stores strings of maximum length 40. I have performed research and found the following code,which creates a dynamic array of integers.
typedef struct {
int *array;
size_t used;
size_t size;
} Array;
void initArray(Array *a, size_t initialSize) {
a->array = malloc(initialSize * sizeof(int));
a->used = 0;
a->size = initialSize;
}
void insertArray(Array *a, int element) {
// a->used is the number of used entries, because a->array[a->used++] updates a->used only *after* the array has been accessed.
// Therefore a->used can go up to a->size
if (a->used == a->size) {
a->size *= 2;
a->array = realloc(a->array, a->size * sizeof(int));
}
a->array[a->used++] = element;
}
void freeArray(Array *a) {
free(a->array);
a->array = NULL;
a->used = a->size = 0;
}
I am currently trying to modify the code, to make it work for my problem. I have so far come up with this
typedef struct {
size_t used;
size_t size;
char *array[][40];
} Array;
void initArray(Array *a, size_t initialSize) {
a->array = malloc(initialSize * sizeof(char));
a->used = 0;
a->size = initialSize;
}
void insertArray(Array *a, char element) {
// a->used is the number of used entries, because a->array[a->used++] updates a->used only *after* the array has been accessed.
// Therefore a->used can go up to a->size
if (a->used == a->size) {
a->size *= 2;
a->array = realloc(a->array, a->size * sizeof(char));
}
strcpy(a->array[a->used++], element);
}
Finally
Array a;
char srcname[40];
initArray(&a, 100);
insertArray(&a, srcname);
This produces a segmentation fault. Although I have researched, I have not managed to make a working dynamic array of strings. Any guidance would be appreciated
char *array[][40]doesn't declare what you think it does. This code shouldn't compile, much less produce a segmentation fault at runtime.