在 C 中初始化指向复合文字的指针

Initializing a pointer to compound literals in C

这是一种不太常见的指针初始化方法:

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

此处,指针指向复合文字。

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

输出:

1

此程序已编译,运行在 G++ 编译器中运行良好。

所以,

是的,有一个指向复合文字的指针是有效的。标准允许这样做。

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.