PDA

View Full Version : why a[10] is not 1.1000


nenyan
Mar1-11, 03:12 PM
#include <stdio.h>
#include <stdlib.h>
int main()
{ double a[10];
int i=0;
for(i=0;i<10;i++)
a[i]=1.1;
a[10]=1.1;
for(i=0;i<10;i++)
printf("a[%d]=%f, ", i, a[i]);

printf("a[10]=%f, ", a[10]);
}

it shows
a[10]=0.000 why not 1.1000?

Borek
Mar1-11, 03:40 PM
a[10] doesn't exist. No idea why it is printed as zero, it must be implementation thing.

nenyan
Mar1-11, 04:34 PM
#include <stdio.h>
#include <stdlib.h>
int main()
{ double a[10];
int i=0;
for(i=0;i<10;i++)
a[i]=1.1;
for(i=0;i<10;i++)
printf("a[%d]=%f, ", i, a[i]);

a[10]=1.1;

printf("a[10]=%f, ", a[10]);
}

then
it shows a[10]=1.1000

I use gcc complier

D H
Mar1-11, 04:44 PM
You declared this variable a as "double a[10]". The only valid indices into "a" are 0 to 9. An index of 10 is invalid.

AlephZero
Mar1-11, 04:45 PM
double a[10] allocates space for 10 doubles. You can access the 10 locations using
a[0], a[1], .... a[9].

If you use a[10], you are accessing a piece of memory doesn't "belong" to you. If the compiler uses that location for something else, then the data you wrote there will be lost. If the compiler doesn't use that location, then you got lucky.

If you want to use a[10] legally, you need to define the array as double a[11].

rcgldr
Mar1-11, 04:45 PM
a[10] is beyond the end of the array which is on the stack. It's possible that the call to printf is storing a zero at that same location on the stack.

nenyan
Mar1-11, 05:20 PM
Thank you. I totally understand.

double a[10] allocates space for 10 doubles. You can access the 10 locations using
a[0], a[1], .... a[9].

If you use a[10], you are accessing a piece of memory doesn't "belong" to you. If the compiler uses that location for something else, then the data you wrote there will be lost. If the compiler doesn't use that location, then you got lucky.

If you want to use a[10] legally, you need to define the array as double a[11].