1 / 6
May 2011

int main()
{
 char s[]="hello world";
 s[20]='x';
 printf("%s %c",s.s[20]);
 return 0;
}

output:
hello world x

but acc to K&R page no 104 ,2nd last para
s is just big enough to hold the sequence of charcters.

Firstly, s.s[20] should be s,s[20].
Memory has contiguous blocks internally. s[20] just point to 20th byte address from s. So s[20] = 'x' will put 'x' at that position. Size of s is indeed size of "hello world". Using s[20] can cause trouble as it might change the value of some other variable or array which already acquires that memory address. So it is better, never to access array index beyond array size.

@vipul
since no other variables are declared
it shud give seg fault..

We will get segmentation fault if its invalid memory reference or system does not allow to access the memory location( e.g locked memory block ).

s[n]='c'
so we can say that ouput will depends on value of "n"
sometimes it may run and sometimes it may give seg fault

Suggested Topics

Topic Category Replies Views Activity
C and C++ 0 13 6d

Want to read more? Browse other topics in C and C++ or view latest topics.