Home > Net >  Cast anonymous two-dimensional array
Cast anonymous two-dimensional array

Time:11-20

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;

CodePudding user response:

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;
}
  • Related