+ 1

In which manner the value of union members got changed? Any one pls!

https://code.sololearn.com/c351sX8EGY9A/?ref=app

9th Jan 2021, 1:26 AM
<Saurabh Singh Rawat/>
<Saurabh Singh Rawat/> - avatar
6 Answers
+ 1
<Saurabh Singh Rawat/> 👋 actually the first 8 bits here (ch[1]), in the memory are the last, and so when the machine read it its read the first 8 bits from right to left (or to precise much more from the low address up to the highest) :v for example : char str[]={'a', 0,0,0} ; means : ._24b__|___8b____ #b=bit 00...000|01100001 str[3:1] | str[0] and as we know the address of str[0] less than str[1,2 or 3] so if we do something like this : int *p = (int*) str; int a=*p ; now the value stored in a is 97 ('a' = 97 ASCII table) .. anyway there is a lot of things i want to tell you about itđŸ„° but.. i suggest to you to read about memory and stack and how they work and stuff like that 👌.. and if you want some help, just ask 😄
9th Jan 2021, 3:35 PM
Amine Laaboudi
Amine Laaboudi - avatar
+ 1
nothing is wrong ,, first you initialize u.i by 2 and then you initialize the array u.ch : 3=11 (in binary representation) 2=10 (in b..) and as we know changing one element from a union variable means changing the first sizeof(element) bytes starting from the add of that element.. and we know that sizeof(short) = sizeof(ch) =2 so when you get the value stored at u.i actually means that you get the hole value in u (cuz sizeof(u) = sizeof(u.i)): it's look like this in memory: u.i=2 |00000000|00000010 at this point if you check out the value stored at ch[0] you will find it = 2 and ch[1] =0. now: ch[0]=3;ch[1]=2; ch[1] ch[0] |00000010|00000011=515
9th Jan 2021, 2:36 AM
Amine Laaboudi
Amine Laaboudi - avatar
+ 1
Wow! Great explanation. Thank you so much. :)
9th Jan 2021, 3:32 AM
<Saurabh Singh Rawat/>
<Saurabh Singh Rawat/> - avatar
+ 1
Amine Laaboudi could you pls tell me one more thing why first 8 bit are allotted to index 1 not 0 here?
9th Jan 2021, 2:36 PM
<Saurabh Singh Rawat/>
<Saurabh Singh Rawat/> - avatar
+ 1
Amine Laaboudi Wow, you explained again well. And yes of course I will read about memory and stack, and if I get any problem, will definitely ask you. You're Awesome! Thanks again.
9th Jan 2021, 3:59 PM
<Saurabh Singh Rawat/>
<Saurabh Singh Rawat/> - avatar
+ 1
<Saurabh Singh Rawat/> you are welcome bro😁
9th Jan 2021, 4:06 PM
Amine Laaboudi
Amine Laaboudi - avatar