在C中初始化一个指向复合文字的指针 [英] Initializing a pointer to compound literals in C

查看:103
本文介绍了在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]);
}

输出:

1

该程序已编译,并且可以在G ++编译器中正常运行.

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

所以

  • 这是初始化复合文字的指针的正确方法吗?或

  • 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):

示例1文件范围定义

EXAMPLE 1 The file scope definition

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

初始化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.

这篇关于在C中初始化一个指向复合文字的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆