View Full Version : why a[10] is not 1.1000
#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?
a[10] doesn't exist. No idea why it is printed as zero, it must be implementation thing.
#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
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].
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.
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].
vBulletin® v3.8.7, Copyright ©2000-2012, vBulletin Solutions, Inc.