I wrote a post earlier about scandir()
, but figured I'd make a new post since I believe the requirement is to only have one question per post.
I'm writing a program that uses scandir()
and getting a incompatible pointer type
warning when I run the program.
According to the man-page for scandir(), the function takes in a "triple pointer" to a dirent struct:
int scandir(const char *dirp, struct dirent ***namelist,
int (*filter)(const struct dirent *),
int (*compar)(const struct dirent **, const struct dirent **));
However, the page also provides the example below:
#define _DEFAULT_SOURCE
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
int
main(void)
{
struct dirent **namelist;
int n;
n = scandir(".", &namelist, NULL, alphasort);
if (n == -1) {
perror("scandir");
exit(EXIT_FAILURE);
}
while (n--) {
printf("%s\n", namelist[n]->d_name);
free(namelist[n]);
}
free(namelist);
exit(EXIT_SUCCESS);
}
In my program, I decided to follow the example and have the code in my program below (distilled to only the statements relevant to scandir()
):
int numOfDirectories = 0;
struct dirent **dirEntries;
numOfDirectories = scandir(".", &dirEntries, NULL, alphasort);
When I run the program, I then get the warning below:
Why would it be giving me this error when I'm essentially following the example it has in the man-page?
Further, according to information received from my other post, passing in &dirEntries
when dirEntries
is a double-pointer should be a triple-pointer.
I did try changing the program by declaring dirEntries
as a triple pointer:
int numOfDirectories = 0;
struct dirent ***dirEntries;
numOfDirectories = scandir(".", dirEntries, NULL, alphasort);
I don't get any compiler errors, but when I run the program I then get a Segmentation fault (core dumped)
error.
I did have a filter function as the 3rd parameter, but decided to just set to NULL in-case it was my filter function causes the error. Still get the same segmentation fault
error using NULL
.
I also tried running the debugger, which it does show this:
Then essentially after I declare my dirEntries
I have an if-statement that is entered and immediately runs numOfDirectories = scandir(".", &dirEntries, NULL, alphasort);
I'm at a loss of what is going on. Any ideas what it could be? Thank you. Appreciate your help and feedback.