Amazon Interview Question
Software Engineer / Developers>>
1) where string literal i.e "SIVA" will be stored ( heap , stack, data or code segments) in above both cases.
str - code segment
str1 - stack
>>
str points to Read only data sigment
@SB : isnt str1 a pointer constant (rather than const ptr). Sections 2 and 3 are perfect!
It depends on the compiler about where it places data.
For ex. 1. On TC, there will be no errors and everything should work fine, so we can say that str is stored in data or stack area (so it can be modified) and str1 is stored in stack area.
2. On GCC, str seems to be stored in read-only section i.e. code area and so it can be modified, whereas str1 is stored on stack. We will encounter run time errors for str as it is stored in code area.
int main(){
char *p = "We";
char *w = p;
w[0] = 'H';
printf("%s", w);
return 0;
}
2,3. Run-Time error in minGW, since we are trying to modify:
char * str = "blah"; //which is equivalent to
const char * str = "blah";
However, note that:
const char * str = "blah";//is not equivalent to
const (char *) str = "blah";
Hope it helps.
10. differences between
- Messi February 09, 2011char *str = "SIVA" and char str1[]="SIVA"
str is a pointer to a constant string. str1 is a constant pointer.
sub questions:
1) where string literal i.e "SIVA" will be stored ( heap , stack, data or code segments) in above both cases.
str - code segment
str1 - stack
2) char *str = "SIVA";
str[0] = 'f' ;
any error ? compile time error or run time error ?
run time error, as you trying to modify a constant string.
3) char *p = (char *) str;
p[0] = 'f' ;
any error ? compile time error or run time error ?
2) reasoning still applies here. runtime error.