【问题标题】:Getting address of rvalue in C99在 C99 中获取右值的地址
【发布时间】:2014-11-17 14:48:04
【问题描述】:

以下代码编译并运行:

#include <stdio.h>

void print(void* x)
{
    printf("%d", *(int*)x);
}

int main()
{
    print(&((struct { int x, y; }){ .x = 1, .y = 2 })); //outputs 1
    return 0;
}

为什么编译器允许我获取右值的地址?这是定义的行为吗?

http://ideone.com/iMwNVr

【问题讨论】:

标签: c gcc c99 undefined-behavior


【解决方案1】:

(struct { int x, y; }){ .x = 1, .y = 2 } 是复合文字,并且:

C99 §6.5.2.5 复合文字

如果类型名称指定一个未知大小的数组,则大小由第 6.7.8 节中指定的初始化列表确定,复合文字的类型是完整数组类型的类型。否则(当类型名称指定对象类型时),复合文字的类型是类型名称指定的类型。在任何一种情况下,结果都是左值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-15
    • 1970-01-01
    • 2017-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多