Search code examples
carrayspointersreturn-type

Returning an array of strings and assigning it to a variable in C


So the problem I am facing is the following:

On one component, I read file names and store them in an array. There can be a maximum of 100 names of maximum 20 characters in length. This is defined as follows:

static Char_t fileList[100][20] = {};

where

fileList[1]= "name1" 
fileList[2]= "name2"  and so on.

By creating a function that returns a pointer to it I want to have access to this array of strings from another component of my code:

Char_t** getAllFiles(void)
{
    return &fileList;
}

And I assign the pointer like this:

Char_t **fileList = getAllFiles();

This does not seem to work. The best I have achieved is to get the pointer to the first component of the array. But I cannot get the rest of the components.


Solution

  • One simple option is to use pointer to array return type.

    Here is a reproducible example:

    #include <stdio.h>
    
    char (*getAllFiles())[];
    
    int main(void)
    {
        char (*str_array)[20] = getAllFiles();
        printf("%s %s", str_array[0], str_array[1]); //test print
    }
    
    char (*getAllFiles())[]
    {
        static char fileList[100][20] = {"name1", "name2"};
        return fileList;
    }
    

    If you don't want/need to use static storage, you can use the same type but with memory allocation, this will allow you to free the memory reserved for your array when you no longer need it. Note that using static storage can have its disadvantages as @RobertS supports Monica Cellio pointed out.

    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    char (*getAllFiles())[];
    
    int main(void)
    {
        char (*str_array)[20] = getAllFiles();
        printf("%s %s", str_array[0], str_array[1]); //test print
        free(str_array); //free the allocated memory after it's used
    }
    
    char (*getAllFiles())[]
    {
        //allocating space for an array of type char, which is always 1 byte, 
        //you must allocate memory according to the array type
        //for instance malloc(sizeof(Char_t) * 100 * 20);
        char (*fileList)[20] = malloc(100 * 20);
    
        strcpy(fileList[0], "name1");
        strcpy(fileList[1], "name2");
    
        return fileList;
    }
    

    Output in both cases:

    name1 name2