简体   繁体   English

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

[英]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. 该程序已编译,并且可以在G ++编译器中正常运行。

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): n1570-§6.5.2.5(p8):

EXAMPLE 1 The file scope definition 示例1文件范围定义

 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. 初始化p指向两个int数组的第一个元素,第一个具有值2,第二个具有值4。 The expressions in this compound literal are required to be constant. 该复合文字中的表达式必须是常量。 The unnamed object has static storage duration . 未命名对象具有静态存储期限

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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