+ 2
Why this code print 10
i am ??????😱 https://code.sololearn.com/c0dd0hqL2Fdc/?ref=app
11 Respuestas
+ 6
I checked his previous posts and you're right Anna. It seems we were quick to judge. :-)
+ 10
Lambda_Driver You'll never get an error for accessing a non existing element of an array in C (at least if the variable belongs to the scope of the program). The integers in the code seem to be stored consecutively like this: b[0], b[1], c, a. That's why "a" can be addressed as b[3] and "c" as b[2].
+ 6
Mihai C you need to change the best answer for this post, I tried messing around with the code and Anna's answer is right.
sree harsha dude chill. I don't code in C so my answer was wrong. I guess I need to study C first before answering any questions about it. Haha.
+ 4
It seems to be a problem with the compiler in SL's server. Normally you should get an error when you access an element in an array that doesn't exist. If you comment out line 7, the program runs without any issues. The weird thing is, if you change line 7 to b[4], b[5] or any other index it gives you the result 3.
+ 4
sree harsha No need to shout. And the question is why the output is 10 (and not 3).
+ 4
Lambda_Driver Shouting seems to be his preferred way of communicating, don't take it personally 😅
+ 4
Earl_Grey I have no idea, but if you try this:
int main() {
int a =3;
int b[]={5,6};
int c = 7;
b[3]= 10;
printf ("%d\n",a);
printf("b[0]: %x\n", &b); // 23fe44
printf("b[1]: %x\n", &b[1]); // 23fe48
printf("b[2]: %x\n", &b[2]); // 23fe4c
printf("b[3]: %x\n", &b[3]); // 23fe50
printf("c: %x\n", &c); // 23fe40
printf("a: %x\n", &a); // 23fe4c
return 0;
}
, you'll see that a and "b[2]" actually have the same memory address (while c, which is declared last, is stored before the array b). It's probably up to the compiler.
+ 3
Anna EH? WHAT'S THAT YOU'RE SAYING?
Lambda_Driver SPEAK UP! I CAN'T HEAR YOU WITH ALL THIS SHOUTING IN HERE! IT'S SO LOUD IN HERE!
😂📣🔊
sree harsha It's not clear if you are aware that using ALL CAPS appears as yelling to many people reading your replies. It's good etiquette to avoid doing this in online communities. 😉
+ 1
Anna, if integers are stored consecutively why 'a' is stored after b[2] but not before b[0]? Variable 'a' was declared before array.
+ 1
Thanks. As I see there is no rule how the variables will be stored. In your example after some changes we have got a second way of data storing.(a is stored at b[2])
We just need to avoid going beyond our array to avoid such problems.
- 1
THERE IS NO PROBLEM WITH THE CODE
OUTPUT WILL BE 3
SINCE b[] IS AN ARRAY CAN TAKE ANY NO OF VALUES
THERE IS NO PROBLEM WITH THE STATEMENT b[3]=10
AS USUALLY VARIABLE a IS STORING 3 AND VARIABLE c IS STORING 7 THESE TWO VARIABLES ARE NORMAL OR INDIVIDUAL VARIABLES THAT CAN STORE ONLY SINGLE VALUES