联合中元素的内存位置

联合中元素的内存位置

本文介绍了C / C ++联合中元素的内存位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C中有一个这样的工会:

I have a union in C like this:

union AUnion {
  struct CharBuf {
    char *buf;
    size_t len;
  } charbuf;
  uint8_t num;
  double fp_num;
};

我的问题是,如果给出以下内容,我可以保证吗:

My question is, can I guarantee that if given the following:

union AUnion u;

则以下条件成立:

&u == &u.num
&u == &u.fp_num
&u == &u.charbuf

即它们都始于 u

I.e they all start at the beginning of the memory segment where u is stored.

对于使用 gcc版本5.3.0 和<$编译的C程序c $ c> -std = c11 以上是正确的:

In the case of this C program compiled with gcc version 5.3.0 and -std=c11 the above is true:

#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>

union AUnion {
    struct CharBuf {
        char *buf;
        size_t len;
    } charbuf;
    uint8_t num;
    double fp_num;
};

int main(void)
{
    union AUnion u;
    printf("%d\n", ((void*)&u) == ((void*)&u.charbuf));
    printf("%d\n", ((void*)&u.charbuf) == ((void*)&u.num));
    printf("%d\n", ((void*)&u.num) == ((void*)&u.fp_num));
}

打印时:

1
1
1

使用相同的编译器将上述代码编译为C ++ 11,其结果与将C11编译为相同的代码。

Compiling the code above as C++11 with the same compiler results in the same output as compiling it as C11.

但这是标准化的行为吗?它是未定义的吗?我可以在大多数C编译器中依赖此行为吗?我还能在C ++编译器中期望这种行为吗?

But is this standardized behaviour? Is it undefined? Can I rely on this behaviour with most C compilers? Can I expect this behaviour with C++ compilers as well?

推荐答案

在 C标准保证:

所以,是的,您可以依赖所有成员,地址从工会开始(请注意,对于结构的第一个成员来说是相同的。)

So, yes, you can rely on all members starting at the unions address (note this is the same for the first member of a struct).

C ++标准包含类似的句子关于C样式(即仅C样式成员) union s / struct s,因为C ++允许将 union 传递给确实需要这种布局的C函数。C++标准的相关部分为9.5。

The C++ standard includes a similar sentence with respect to C-style (i.e. only C-style members) unions/structs, because C++ allows to pass unions to C functions which does require this layout.The relevant section in the C++ standard is 9.5.

但是,请注意,标准简单类型(整数,浮点数)内可能会填充。并且它们的内部可能会有所不同(倾向)。您还可能违反严格的别名规则(C:有效类型)。

However, note there might be padding bits inside standard simple types (integers, floats). And their internal may vary (endianess). You also might violate strict aliasing rule (C: effective type).

这篇关于C / C ++联合中元素的内存位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-13 13:10