arraysc

Uninitialized array literal


I want to create a pointer that is either an array or a null pointer. Something like

int * arr = (condition) ? int[var] : NULL

but there doesn't seem to be a way of declaring an unnamed, uninitialized, non-constant length array.

I know that I could do it in multiple steps by starting with an uninitialized array and later setting it to NULL based on the condition, but this seems inelegant. I also know I could use malloc(), but then I must manually free that space.

It seems to me that, since an array is just a pointer to the first element, what I want is not logically inconsistent with C, but I could be wrong.

Is it possible to achieve this in standard C? Is there a fundamental reason why it couldn't work?


Solution

  • If the array was a fixed size, you could do this with a compound literal:

    int *arr = condition ? (int[5]){} : NULL;
    

    However you want to use a variable length array. Such arrays can't be initialized (until C23, in which empty initialization of VLAs is allowed and would be = {}), and as a result a compound literal can't be built for a VLA.

    You'll need to stick with one of the alternate methods you proposed, either creating the array and setting the pointer separately:

    int size = condition ? var : 1;
    int a[size];
    int *arr = condition ? a : NULL;
    

    Or using malloc:

    int *arr = condition ? malloc(var * sizeof *arr) : NULL;