Search code examples
cpointerscompound-literals

Initializing a pointer to compound literals in C


Here is one not-so-common way of initializing the pointer:

int *p = (int[10]){[1]=1};

Here, pointer point to compound literals.

#include <stdio.h>
int main(void)
{
    int *p = (int[10]){[1]=1};
    printf("%d\n", p[1]);
}

Output:

1

This program is compiled and run fine in G++ compiler.

So,

  • Is it the correct way to initializing a pointer to compound literals? or

  • Is it undefined behaviour initialize pointer to compound literals?


Solution

  • Yes, it is valid to have a pointer to compound literals. Standard allows this.

    n1570-§6.5.2.5 (p8):

    EXAMPLE 1 The file scope definition

    int *p = (int []){2, 4};
    

    initializes p to point to the first element of an array of two ints, the first having the value two and the second, four. The expressions in this compound literal are required to be constant. The unnamed object has static storage duration.