Question

char*[] makeList(char *path, int *noOfFiles);

I think my intentions are clear but this doesn't work.

P.S. I need to store the return value in a variable called char *fileList[260] and not char** fileList.

Was it helpful?

Solution

It is not possible to return an array of pointers from a function unless it is wrapped inside struct. If you tried to return an array, it would decay into a pointer value, so the return result would actually be a pointer.

Even if you managed to return an array of pointers somehow, you would not be able to assign it to the variable fileList if it is defined as char *fileList[260]. As fileList is an array type, you are forbidden from assigning to an array.

If you want a function to modify the contents of an array (or populate the array), you need to pass the array to the function.

int makeList(char *path, int *noOfFiles, char *listOfFiles[], int maxFileCount);

/*...*/
char *fileList[260];
int fileCount;
int result = makeList("/some/path", &fileCount, fileList,
                      sizeof(fileList)/sizeof(*fileList));

Your makeList() function should make sure it does not write more than maxFileCount entries into listOfFiles. It can return a result indicating that it needs a larger array if there are more files to return than what the array passed in can hold.

OTHER TIPS

char *fileList[] and char **fileList are (or can be, anyway) functionally the same. In C, if you are passing or returning arrays, you should (probably) be using only pointers. There are some instances where it is allowed to use arrays (namely if the length of the array is known at compile-time), but it's (in my opinion) easier to just get comfortable with pointers.

Also, this question has more or less been answered already: Declaring a C function to return an array

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top