+ 3

How does this work

I was looking at the lessons for C and was playing around with the code and tried this: #include <stdio.h> int main() { int x[] = {20, 45, 16, 18, 22}; x[1] = 260; x[7] = 370; printf("The second element is %d\n", x[1]); /* 260 */ printf("The 8th element is %d\n", x[7]); printf("The 7th element is %d\n", x[6]); return 0; } Why does it say that the last output's value is 8? https://code.sololearn.com/cw5k953k8s94/?ref=app

23rd Mar 2018, 9:09 PM
Galen Schick
Galen Schick - avatar
9 Respostas
+ 8
Modifying elements beyond the array bounds introduces bugs into the program. Note how I modified b[3] and the value of a changed. This is the worst type of bug to track down. https://code.sololearn.com/cqImm6YcHWd4
24th Mar 2018, 12:25 AM
John Wells
John Wells - avatar
+ 5
It's some Garbage value... Paul had written a code about it too in C++... (sorry to bother you bro) https://code.sololearn.com/c6AUk70emKRg/?ref=app
24th Nov 2018, 10:59 AM
$hardul B
$hardul B - avatar
+ 3
@Saad OK thanks
23rd Mar 2018, 9:20 PM
Galen Schick
Galen Schick - avatar
+ 2
Its a dummy value. It is auto assigned. There will be something in x[5] and x[8] too.. It is to prevent memory leak. That’s why it is recommended to assign every value or use arrays in sequence
23rd Mar 2018, 9:19 PM
Saad
Saad - avatar
+ 2
Yes, you failed to assign a value. But the reason you get that value is that an array (or variable) that's not initialised will _contain whatever values were left in memory_ prior to declaration. Values are the same on SL because the playground is probably emulated. On a PC these values _may change_ after running another program or rebooting. Note: you shouldn't be accessing that area of memory at all since x was declared as having 5 elements.
23rd Mar 2018, 10:27 PM
non
+ 2
True! Asterisk
24th Nov 2018, 11:56 AM
$hardul B
$hardul B - avatar
+ 1
When did you assign any value to x[6]?
23rd Mar 2018, 9:13 PM
Saad
Saad - avatar
+ 1
I didnt
23rd Mar 2018, 9:13 PM
Galen Schick
Galen Schick - avatar
+ 1
yeh its garbage value $hardul Birje but it seem that of sololearn is given an integer as it garbage value that why it seem confusing, while that of a computer will be given hexadecimal value as it garbage value
24th Nov 2018, 11:55 AM
✳AsterisK✳
✳AsterisK✳ - avatar