簡體   English   中英

C 字符串和字符

[英]C strings and chars

代碼 A:

char* str="hello";
str[2]='!';
printf("%s\n", str);

在這段代碼中,程序編譯並運行但得到一個運行時錯誤:”

但是,如果編寫以下代碼(代碼 B):

char str[10]="hello";
str[2]='!';
printf("%s\n", str);

然后,一切都很好。 程序運行並輸出“he!lo”。

我不明白代碼 A 和代碼 B 之間的差異如何影響編譯器的行為。

據我所知,指向數組的指針指向數組中的第一個元素(意思是指向字符 'h' 所在的位置,任何數組的元素都可以使用以下行進行更改: str[2]='!';在代碼 B 中,這一行工作正常!那么......為什么在代碼 A 中它不是很好?

第二個在堆棧上創建 10 個字節(可寫),並在該分配中放置 hello 和結尾零。 第一個在堆棧上創建一個指針,指向位於某處的“hello”字符串。 在您的情況下,它可能在未標記為可寫的內存中創建它,因此您的程序在運行時崩潰了。

char* str="hello";

或者

compiler, give me a reference to this sequence of chars in memory
do not care if it is read-only memory, just give me the damn pointer!

==

char str[10]="hello";

或者

compiler, please allocate an array of 10 chars for me
and please initialize it with "hello".

不允許修改,除非你聲明為 str[] = "hello"。 請看這篇文章: assign a string value to pointer

暫無
暫無

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

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