Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast anonymous two-dimensional array

Is it possible to create an anonymous array like this?

char **values = (*char[]){"aaa", "bbb", "ccc"};

This method works:

char **values
char *tmp[] = {"aaa", "bbb", "ccc"};
values = tmp;
like image 333
bartool Avatar asked Oct 20 '25 11:10

bartool


1 Answers

Yes, you can do this using a compound literal (which creates an anonymous object whose address can be taken). You just need to get the type of that compound literal correct (in your case it will be char*[]), then take its address using the & operator:

#include <stdio.h>

int main()
{
    // The outer brackets on the RHS are not necessary but added for clarity...
    char *(*values)[3] = &( (char* []) { "aaa", "bbb", "ccc" } );
    for (int i = 0; i < 3; ++i) printf("%s\n", (*values)[i]);
    return 0;
}

Alternatively, you could take advantage of the fact that an array (even one defined as a compound literal) will automatically 'decay' to a pointer to its first element (in most circumstances, including when used as the RHS of an assignment operation):

int main()
{
    char** values = (char* []){ "aaa", "bbb", "ccc" };
    for (int i = 0; i < 3; ++i) printf("%s\n", values[i]);
    return 0;
}
like image 187
Adrian Mole Avatar answered Oct 23 '25 02:10

Adrian Mole