简体   繁体   中英

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM