Your code would produce undefined behaviour or most probably crash. That's because FileNames
is a pointer to a character, not to a memory buffer to copy your strings into and the function strcpy
does not do bounds checking for the buffer being copied into. So strcpy
will try to write into the memory you have not allocated for the purpose. You need to allocate memory to copy the file names first.
#define MAX_FILE_NUM 1000
char *FileNames[MAX_FILE_NUM] = {0}; // initialize to NULL
int Counter = 0;
while((DirentPointer = readdir(DirectoryPointer)) != NULL) {
FileNames[counter] = malloc(strlen(DirentPointer->d_name) + 1); // + 1 for the null byte
// check for NULL
if(FileNames[i] != NULL) {
strcpy(FileNames[i], DirentPointer->d_name);
Counter++;
}
else {
// handle the NULL case
// maybe try malloc again
}
}
// after you are done with the FileNames
for(int i = 0; i < Counter; i++) {
free(FileNames[i]);
FileNames[i] = NULL;
}