c - Functioning of Arrays -


here 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 output of 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 have 2 questions:

1- why num[5] num[9] displayed there values 0?

2- why num[10] num[14] displaying these values, when have declared length int num [10] , not int num [15], shouldn't program displaying error while running or compiling?

here program doing:

int num[10] = {10,20,30,40,50} 

the above line tells compiler create array of ten integers , initialize first 5 values (indices 0-4) ones provided. remainder of values (indices 5-9) automatically initialized 0 per c99 specification.

num[9] # value allocated , initialized. num[10] # value neither allocated nor initialized exists anyway. 

when num[9] telling compiler access integer 9 integers away start of array called num, in fact, it's same saying *(num+(int*)9).

it's pure luck can access 10th through 15th values - didn't ask compiler allocate space it's there anyway, , computer doesn't prevent looking @ it.

in summary, have discovered fact c language doesn't prevent accessing values have not initialized or asked allocate!


Comments

Popular posts from this blog

google api - Incomplete response from Gmail API threads.list -

Installing Android SQLite Asset Helper -

Qt Creator - Searching files with Locator including folder -