联合和结构初始化 [英] Union and Struct Initialization

查看:33
本文介绍了联合和结构初始化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我偶然发现了一个基于 C 中联合的代码.代码如下:

I stumbled across a code based on unions in C. Here is the code:

    union    {  
        struct  {  
            char ax[2];  
            char ab[2];  
        } s;  
        struct  {  
            int a;  
            int b;  
        } st;  
    } u ={12, 1}; 

    printf("%d %d", u.st.a, u.st.b);  

我就是不明白为什么输出是 268 0.这些值是如何初始化的?工会在这里如何运作?输出不应该是12 1.如果有人能详细解释这里到底发生了什么,那就太好了.

I just couldn't understand how come the output was 268 0. How were the values initialized? How is the union functioning here? Shouldn't the output be 12 1. It would be great if anyone could explain what exactly is happening here in detail.

我使用的是 32 位处理器和 Windows 7.

I am using a 32 bit processor and on Windows 7.

推荐答案

代码与您想的不一样.Brace-initializes 初始化 first 联合成员,即 u.s.但是,现在初始化程序不完整且缺少大括号,因为 u.s 包含两个数组.它应该是这样的: u = { { {'a', 'b'}, { 'c', 'd' } } };

The code doesn't do what you think. Brace-initializes initialize the first union member, i.e. u.s. However, now the initializer is incomplete and missing braces, since u.s contains two arrays. It should be somethink like: u = { { {'a', 'b'}, { 'c', 'd' } } };

你应该总是编译时出现所有警告,一个体面的编译器应该告诉你有什么地方不对劲.例如,GCC 说,缺少初始化程序周围的大括号('u.s' 的初始化附近)缺少初始化程序('u.s.ab' 的初始化附近).很有帮助.

You should always compile with all warnings, a decent compiler should have told you that something was amiss. For instance, GCC says, missing braces around initialiser (near initialisation for ‘u.s’) and missing initialiser (near initialisation for ‘u.s.ab’). Very helpful.

在 C99 中,您可以利用命名成员初始化来初始化第二个联合成员:u = { .st = {12, 1} };(这在 C++ 中是不可能的,由方式.)第一种情况的对应语法是 `u = { .s = { {'a', 'b'}, { 'c', 'd' } } };,其中可以说更明确和可读!

In C99 you can take advantage of named member initialization to initialize the second union member: u = { .st = {12, 1} }; (This is not possible in C++, by the way.) The corresponding syntax for the first case is `u = { .s = { {'a', 'b'}, { 'c', 'd' } } };, which is arguably more explicit and readable!

这篇关于联合和结构初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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