Why this code does not work?
int main(){
char *str ="abcde";
scanf("%s",str);
printf("%s",str);
}
but this works?
int main(){
char str[] ="abcde";
scanf("%s",str);
printf("%s",str);
}`
Why this code does not work?
int main(){
char *str ="abcde";
scanf("%s",str);
printf("%s",str);
}
but this works?
int main(){
char str[] ="abcde";
scanf("%s",str);
printf("%s",str);
}`
In the first code, you declare a pointer, which points to a string literal: "abcde"
.
This might be a constant, and you will not be able to change it.
The second code is declaring an array and filling it with ['a','b',c','d','e','\0']
, and is not a constant - so you can change it.
Because char *str ="abcde";
is a pointer to string literal which is most likely stored in read-only memory.
char str[] ="abcde";
is an array initialized with "abcde"
.
You should also check out Difference between char* and char[]
When string value is directly assigned to a pointer, it’s stored in a read only block(generally in data segment) that is shared among functions
char *str = "GfG";
...
char str[] = "GfG"; /* Stored in stack segment like other auto variables */ *(str+1) = 'n'; /* No problem: String is now GnG */