简体   繁体   中英

character pointer

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 */ 

http://www.geeksforgeeks.org/archives/5328

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM