I'm using the dirent.h library to scan a directory for all the files it contains and store pointers to the resulting objects in an array. I've been following this old SO question describing the storage of structure pointers in arrays, but I'm running into issues during my implementation.
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
int main(int argc, char **argv)
{
DIR *d = NULL;
struct dirent *dir = NULL;
struct dirent *d_array[50]; //big overkill array to avoid realloc
size_t n = 0; //number of items
d = opendir("scandir"); //name of directory to search
if(d)
{
while((dir = readdir(d))!=NULL) {
//d_array[n] = malloc(sizeof(struct dirent));
d_array[n++] = dir;
}
closedir(d);
}
for(size_t i = 0;i<n;i++) {
printf(d_array[n]->d_name);
free(d_array[n]);
}
free(d_array);
return 0;
}
Running the above code results in a Segmentation fault: 11. I thought this was probably because I was properly allocating the memory for the structures (as seen in the commented out malloc), but including that gives the following error:
error: assigning to 'struct dirent *' from incompatible type
'void *'
I don't understand why d_array[n] = malloc(sizeof(struct dirent))
, which is verbatim from multiple posts about this topic, is having this incompatible type error. And if it's inappropriate to use, why am I getting a segfault?