C語言中char s[] 和 char *s的區別

有關於這兩者的區別,下面的來自Stack Overflow的解釋非常清晰:
http://stackoverflow.com/questions/1704407/what-is-the-difference-between-char-s-and-char-s-in-c

The difference here is that

char *s = "Hello world";

will place Hello world in the read-only parts of the memory and making s a pointer to that, making any writing operation on this memory illegal. While doing:

char s[] = "Hello world";

puts the literal string in read-only memory and copies the string to newly allocated memory on the stack. Thus makings[0] = 'J' legal.


總結一下,要點如下:

  1. char [] 定義的是字符串數組,該字符數組在內存中的存儲是先分配新空間,再去填充,因此該數組的內容可以改變,即通過s[0] = 'J'是合法的。
  2. char *s定義的是字符串指針變量,該指針變量指向一個字符串,該指針的值是該字符串在內存中的地址。對於這個指針變量來說,改變它的值=改變地址=改變指針指向,比如從指向第一個字符變爲指向第二個字符。然後改字符指針變量並沒有權力去更改它指向的字符的值,比如*(s+1) = 'J'。換句話說,就是可以修改指針的值,但不能修改指針值的值。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章