Initializing a pointer to compound literals in C

醉酒当歌 提交于 2019-12-08 05:19:06

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/46557537/initializing-a-pointer-to-compound-literals-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!