Why is a[10] not equal to 1.1000?

  • Thread starter Thread starter nenyan
  • Start date Start date
AI Thread Summary
The discussion centers around the behavior of an array in C programming, specifically when accessing an out-of-bounds index. The code snippet defines an array `a` of size 10, allowing valid indices from 0 to 9. Accessing `a[10]` is invalid, as it exceeds the allocated memory for the array. When `a[10]` is printed, it may show unexpected results, such as 0.000, due to the compiler's handling of memory. This behavior can vary depending on the compiler and the state of the memory at that location. To legally access the 11th element, the array should be defined with a size of 11, i.e., `double a[11]`. The discussion emphasizes the importance of understanding array bounds to avoid undefined behavior in C.
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?
 
Technology 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
 
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.
 
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].
 
Back
Top