Why is a[10] not equal to 1.1000?

  • Thread starter Thread starter nenyan
  • Start date Start date
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
6 replies · 2K views
nenyan
Messages
67
Reaction score
0
#include <stdio.h>
#include <stdlib.h>
int main()
{ double a[10];
int i=0;
for(i=0;i<10;i++)
a=1.1;
a[10]=1.1;
for(i=0;i<10;i++)
printf("a[%d]=%f, ", i, a);

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

it shows
a[10]=0.000 why not 1.1000?
 
Physics news on Phys.org
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=1.1;
for(i=0;i<10;i++)
printf("a[%d]=%f, ", i, a);

a[10]=1.1;

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

then
it shows a[10]=1.1000

I use gcc complier
 
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.

AlephZero said:
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].