4

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;
bartool
  • 43
  • 4
  • 2
    If you do find a way to create such an array directly, you should probably terminate it with `NULL`, else there will be no way to find the end: `char **values = (*char[]){"aaa", "bbb", "ccc", NULL};` – Andrew Henle Nov 19 '22 at 13:25
  • 1
    Re “`(*char[]){"aaa", "bbb", "ccc"}`”: Is that a typo; do you mean `(char *[]){"aaa", "bbb", "ccc"}`? – Eric Postpischil Nov 19 '22 at 13:26
  • No, it isn't. I thought it was correct. – bartool Nov 19 '22 at 14:41

1 Answers1

5

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;
}
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
  • 2
    There is nothing wrong with `char **`, except for the typo in the question (`*char` instead of `char *`). The compound literal `(char *[]) {"aaa", "bbb", "ccc"}` is an array that will be automatically converted to `char **`. – Eric Postpischil Nov 19 '22 at 13:27
  • @Eric Yes, indeed. After some fumbling and confusion-resolution, I have offered that as an alternative. ;-) – Adrian Mole Nov 19 '22 at 13:39