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'。换句话说,就是可以修改指针的值,但不能修改指针指向的值。

你可能感兴趣的:(C语言编程注意点)