+ 12

How does the program output 10?

C Quiz by *Asterisk* https://code.sololearn.com/cU8K0X4CldP2/?ref=app

31st Dec 2018, 11:28 AM
silentlearner
silentlearner - avatar
7 Respuestas
+ 15
You might get other results if you try to run the code in different compilers. It looks like the values of b[0], b[1], c and a are stored in four consecutive memory locations, so by changing b[2] you're effectively changing c and by changing b[3] you're changing a.
31st Dec 2018, 12:19 PM
Anna
Anna - avatar
+ 8
silentlearner you post a good question. The stated C quiz question is a poor one and should be removed IMHO. Anna has given you the correct explanation already.
1st Jan 2019, 10:56 PM
Sonic
Sonic - avatar
+ 6
You are accessing a place beyond the range of your array (it only goes up to b[1], so you hit a place in memory where something else is stored (in this case your variable a).
31st Dec 2018, 12:23 PM
HonFu
HonFu - avatar
+ 5
you lucky that a and b[3] have the same address. its compiler dependent. if storage is layed out form the top down as (a, c, b[1], b[0]) , then changing b[3] will change a. this is bad programing practice to overrun arrays.
2nd Jan 2019, 3:23 PM
Rick Shiffman
Rick Shiffman - avatar
+ 2
Thomas, b[3] accesses the 4th element, so size of array should be >= 4.
31st Dec 2018, 12:35 PM
HonFu
HonFu - avatar
0
Try this and see b[1] = 10 or b[2] =10
2nd Jan 2019, 11:47 PM
✳AsterisK✳
✳AsterisK✳ - avatar
0
Anna good answer, it make sense.. can you explain in which order the memmory is allocated for auto variable s inside a function..?
11th Feb 2019, 4:51 PM
punnoose