Yahoo Interview Question
Software Engineer / DevelopersCountry: United States
Interview Type: Phone Interview
String literals cannot be changed in C. The behavior in this case is undefined. Your char* c is pointing to a string literal. It is a really good idea to define char* c as const char* c to catch this kind of error during compile time. Or initialize an array, rather than a pointer with the literal if you'll change it later, as in char c[10] = "abc".
In the previous case char*c is a const char*. Lets say we change it to be char* const c, which makes it a constant pointer to a character. SO by definition you should now be able to change the value but you cant make c point to anything else right?
The below code doesnt print c either.
char* const c = "assa";
*c ="ghj";
printf("%s",c);
Also as far as I know, when you declare an array or a pointer to an array, it is basically a constant pointer to a int/char whatever. There's no reason why it shouldn't allow you to change the value being pointed to. This thing is driving me nuts. Can some explain please?
For heaven's sake STOP! using TurboC. The program should crash if compiled with a decent compiler.
c is a pointer to a read only location. It is in .text segment and not .bss since "abc" is a literal. Attempt to write there should crash the program.
- Anonymous March 26, 2012