Saturday, December 30, 2006

String Constants

char *a = "abc";
a = "def";

The above is correct but the code crashes when we do a[1] = 'd';

This may be because actually when we say char * a ="abc"; then it means a is pointing to a const memory location which contains "abc" and when we say a= "def"; its again modifying pointer's value to be now pointing to some other constant location; but when u\we say a[1]= 'd' then we are modyfying a const so it crashes!
C doesnot defines behaviour when you chnage a string literal that is why it is crashing.You will end up getting different results with different compilers or on diff machines too.

No comments: