I'm a c++ beginner.I have a basic question.

Asked 2 years ago, Updated 2 years ago, 26 views

Finally uni in the following code.What would be the value of i? Let's answer in hexadecimal. union UNI {
int i; char c; } } uni; uni.i = 0x12345678; uni.c = 0x90;

Answer: Changing the value of 0x12345690 uni.c is uni.Same as changing the last byte of i.

It's written on the answer sheet, but from my point of view as a beginner, why uni?I don't understand if uni.c is after i. In front of a self-taught book, I learned that Union, a common entity, puts several types of variables in the same address, and if one variable changes, other types of variables are also affected. But why are you here, uni.I don't know if i becomes 0x1234567890 because it doesn't match the value of uni.c, which is later initialized. Please answer the questions from the masters. And if you have any tips on learning c++ in detail for self-taught people, please introduce it. I am not a major, but I am in pain because there is no additional explanation and my answer is poor.

c++

2022-09-22 19:27

2 Answers

http://itguru.tistory.com/71

If you go in here, you can find the answer you want.

I recommend you to look at C language first and then C++ on this site.


2022-09-22 19:27

Union is looking at the same memory as a different data type.

Uni.i and uni.c point to the same address, and the actual memory location is the same.

Since uni.i is int type, it occupies 32 bits (4 bytes) and can access all 0x12 / 0x34 / 0x56 / 0x784 bytes, whereas uni.c is the char data type, so it can only access 0x78 which is one of those four memory addresses (1 bytes).

Alignment starts from the front. But where this is going can be different depending on the structure of the computer structure. Whether uni.c points to a memory location with 0x12 or a memory location with 0x78 depends on whether it is Big Endian or Little Endian. I recommend you look up "Endian."


2022-09-22 19:27

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.