Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

character pointer

Tags:

c

string

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);
}`
like image 586
code4fun Avatar asked Jul 26 '26 10:07

code4fun


2 Answers

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.

like image 176
amit Avatar answered Jul 29 '26 00:07

amit


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[]

like image 25
LihO Avatar answered Jul 28 '26 23:07

LihO



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!