Reputation: 1024
Here is an Array program.
Practice.c
#include <stdio.h>
void main()
{
int i,num[10]={10,20,30,40,50};
for(i=0;i<15;i++)
{
printf("\nnum[%d] =%d",i,num[i]);
}
}
Following is the output of the Program.
num[0] =10
num[1] =20
num[2] =30
num[3] =40
num[4] =50
num[5] =0
num[6] =0
num[7] =0
num[8] =0
num[9] =0
num[10] =10
num[11] =0
num[12] =2686711
num[13] =2686820
num[14] =4199443
Now I have 2 questions:
1- Why is num[5] to num[9]
displayed there values as 0
?
2- Why num[10] to num[14]
are displaying these values, when I only have declared the length as int num [10]
and not as int num [15]
, shouldn't the program be displaying an error while running or compiling?
Upvotes: 2
Views: 78
Reputation: 156652
Here is what your program is doing:
int num[10] = {10,20,30,40,50}
The above line tells the compiler to create an array of ten integers and initialize the first five values (indices 0-4) to the ones you provided. The remainder of the values (indices 5-9) are automatically initialized to zero per the C99 specification.
num[9] # This value was specifically allocated and initialized.
num[10] # This value was neither allocated nor initialized but it exists anyway.
When you say num[9]
you are telling the compiler to access the integer that is nine integers away from the start of the array called num
, in fact, it's almost exactly the same as saying *(num+(int*)9)
.
It's pure luck that you can access the 10th through 15th values - you didn't ask the compiler to allocate that space but it's there anyway, and the computer doesn't prevent you from looking at it.
In summary, you have just discovered the fact that the C language doesn't prevent you from accessing values that you have not initialized or specifically asked to allocate!
Upvotes: 4