Wednesday, 15 May 2013

c - Segmentation Fault & printing an array without loops -



c - Segmentation Fault & printing an array without loops -

i'm trying run simple programme count number of spaces, digits , other characters using arrays. below program:

void main(){ int digit_holders[10]={0}; int ch; int i, white_space=0,other=0; while((ch=getchar())!=eof){ if(isspace(ch)) white_space++; else if(isdigit(ch)) digit_holders[ch-'0']++; else other++; } digit_holders[12]=20; printf("\n white spaces=%d\n other=%d\n",white_space,other); for(i=0;i<=9;i++) printf("\ndigit_holders[%d]=%d\n",i,digit_holders[i]); printf("\n digit_holder[12]=%d\n",digit_holders[12]); }

2 questions:

why digit_holders[12] still manage print assigned vale despite beingness outside range? why doesn't display segmentation fault ?the same happens when alter loop check i<=11 manages print digit_holders[11]=0 ( shouldn't) .. when replace 11/10 1100 i.e digit_holders[1100] in either of case, programme crashes ( segmentation fault). why ? is there easier way print elements of array without using loop ?

-thanks!

there no range checking in c gives best shot (i.e plenty rope hang , rest of family).

segmentation fault occurs os. i.e. trying access memory not assigned process.

c arrays

No comments:

Post a Comment