簡體   English   中英

為什么scanf看起來像改變了char *的行為?

[英]Why does a scanf look like it changes the behaviour of char*?

我有以下代碼,很難理解它為什么以這種方式工作:

char* str = "HELLO";
printf("%s",&str[0]); //Returns Hello as expected
printf("%c",str[2]); //Returns L as aspected
scanf("%s",&str); //I enter aaaa
printf("%s\n",&str); /* If I want to access the word I have to do this way
&str[0] now gives a segmentation fault.*/
printf("%c\n",&str[1]); /*This gives a b???!!!. I haven't found any way to 
access individual character with *str.*/

我對為什么似乎無法訪問各個字符特別感興趣,盡管從某種意義上說,盡管這樣做很有意義,但畢竟應該聲明一個指向char的指針,但我想知道它如何在字符串中用作字符串某種方式。 但是我想知道為什么第一個按預期的那樣作為字符數組工作,而不是第二個。

謝謝。

scanf("%s",&str); 調用未定義的行為:您要求scanf讀取一個字符串並將其存儲在str指針本身的位置,而不是它指向的位置,這是一個字符串文字,也不應修改。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM