Search code examples
carraysmultidimensional-arraycompound-literals

C error: taking address of temporary array


I am passing a two-dimensional char array as a compound literal into a method but am receiving the error:

error: taking address of temporary array

Does this have anything to do with the way the variable is being declared in the method declaration or is it something else?

void printConcatLine(char chunks[][20]) { }

printConcatLine((char*[]){ "{", "255", "}" });

Solution

  • I am passing a two-dimensional char array

    No you are passing the pointer to an array of char * pointers.

    The correct version:

    void printConcatLine(char *chunks[]) 
    { 
        while(*chunks) 
        {
            printf("%s", *chunks++);
        }
        printf("\n");
    }
    
    int main(void)
    {
        printConcatLine((char*[]){ "{", "255", "}", NULL });
    }
    

    https://godbolt.org/z/sjxKpj

    or

    void printConcatLine(char chunks[][20]) 
    { 
        for(size_t index = 0; strlen(chunks[index]);index++) 
        {
            printf("%s", chunks[index]);
        }
        printf("\n");
    }
    
    int main(void)
    {
        printConcatLine((char[][20]){ "{", "255", "}", "" });
    }
    

    https://godbolt.org/z/76ca71

    In both cases you need to pass the number of the pointers/length of the array or terminate it somehow (as in my examples). C does not have any mechanism to retrieve the length of the passed array.