简体   繁体   English

通过使用int和char数组的联合找到int值,但是这个值是怎么来的?可以告诉任何人吗?

[英]By using union of int and char array finding the int value,but how this value is coming ?can tell anyone?

I have written c++ code for understanding union concept.In the code I have assigned some character to char array and print the int value,but I don't understand the its logic behind.need help?我已经编写了 c++ 代码来理解联合概念。在代码中,我将一些字符分配给 char 数组并打印 int 值,但我不明白其背后的逻辑。需要帮助吗? below code I have written.下面是我写的代码。

#include <iostream>
union float_u {
    int f;
   char a[sizeof(int)];
} data1;

  using namespace std;

int main()
{


    cout << "Size of union :" << sizeof(data1)<<endl;

   data1.a[0] = '@';
   data1.a[1]= '@';


   cout << "value of f :" << data1.f << endl;

   return 0;
 }

Output coming like this: Output 是这样的:

Size of union:4工会规模:4

value of f:16448 f 的值:16448

You cannot understand C++ by writing code and studying its output. Thats because there are just too many ways to write C++ code that compiles without error, but has undefined bahvior.你无法通过编写代码并研究它的 output 来理解 C++。那是因为有太多方法可以编写 C++ 编译无误但具有未定义行为的代码。

I am quoting from https://en.cppreference.com/w/cpp/language/union .我引用自https://en.cppreference.com/w/cpp/language/union

It is undefined behavior to read from the member of the union that wasn't most recently written.从不是最近写入的联合成员中读取是未定义的行为。

You are writing to a .您正在写信a . a is the active member of the union. a是工会的活跃成员。 Reading from f is undefined.f读取未定义。 You could in principle get any output.原则上您可以获得任何 output。

Many compilers implement, as a non-standard language extension, the ability to read inactive members of a union.许多编译器作为非标准语言扩展实现了读取联合的非活动成员的能力。

As far as I know type punning via unions is allowed in C, so its not too difficult for compilers to also allow it in C++. Though, when you make use of a compiler extension you need to be aware that it isnt standard portable C++, and you need to read your compilers manual.据我所知,在 C 中允许通过联合进行类型双关,因此编译器在 C++ 中也允许它并不难。但是,当您使用编译器扩展时,您需要注意它不是标准的可移植 C++,你需要阅读你的编译器手册。

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

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