Hi I'm trying to store command line arguments of unknown amount into a dynamically allocated array of strings in c. The terminal is telling me I have a segFault which I have tracked down to a strcpy line(see code 1.) I've tried looking at other peoples solutions but I'm still not sure what I have done wrong, but I believe I have a memory leak.
code 1.
for (int j = fileLocCount+1; j < argc; j++){
strcpy(filelist.array[filelist.used], argv[j]);
filelist.used += 1;
if (filelist.used == filelist.size){
for (int i = 0; i < 100; i++)
insertArray(&filelist, i);
}
}
//printArray(&filelist);
freeArray(&filelist);
the 'filelist' variable is a struct called Array
typedef struct {
char **array;
size_t used;
size_t size;
} Array;
and has the functions
void initArray(Array *a, size_t initialSize) {
a->array = (char **) calloc(initialSize, 255);
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++] = a->array[element];
}
void freeArray(Array *a) {
free(a->array);
a->array = NULL;
a->used = a->size = 0;
}
Any help is really really appreciated
Edit:255bit in calloc was just a abnormally large number for debugging mainly this was actually a typo and was meant to have been 256bit for the \0. The reason I couldn’t just refer to the argv[i] and argc was because I need to pass an unknown amount of filepaths(the values I am storing) to a function in another c file. Thanks for all the answers I really appreciate it.
Edit 2: just realised that I was silly for doing it this way and completely forgot that I should have just created an array of size = argc-(num(command line arguments that aren't what I wanted) just for anyone else in this situation. But it won't go to waste I will use dynamic arrays further down the line thank you guys.