0

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", "}" });

2 Answers2

2

"I am passing a two-dimensional char array" --> No. code is passing the address of of a char *.

Pass a matching type

// printConcatLine((char*[]){ "{", "255", "}" });
printConcatLine((char[][20]){ "{", "255", "}" });
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
2

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.

0___________
  • 60,014
  • 4
  • 34
  • 74