我真的很困惑在字符串上使用指针。 感觉他们遵守不同的规则。 考虑以下代码
-
char *ptr = "apple";// perfectly valid here not when declaring afterwards like next ptr = "apple"; // shouldn't it be *ptr = "apple"
printf()
的行为也不同 -printf("%s", ptr) // Why should I send the address instead of the value
另外我在一本书中看到了下面的代码
char str[]="Quest"; char *p="Quest"; str++; // error, constant pointer can't change *str='Z'; // works, because pointer is not constant p++; // works, because pointer is not constant *p = 'M'; // error, because string is constant
我不明白这是什么意思
请帮忙,我在别处找不到任何信息
最佳答案
char *ptr;
ptr = "apple"; // shouldn't it be *ptr = "apple"
不,因为 *ptr
将是一个 char
。所以,你可以写 *ptr = 'a'
但你不能按照你的建议写。
printf("%s", ptr) // Why should I send the address instead of the value
因为 C 中的字符串是以零结尾的字符序列 (char
) 的地址(空字符又名 \x0
)。
char str[] = "Quest";
char *p = "Quest";
str++; // error, constant pointer can't change
不,指针可以完美改变,但这里,str
是一个数组(与指针略有不同)。但是,因此,它不能处理指针运算。
*str='Z'; // works, because pointer is not constant
不,它可以工作,因为 *str
应该是 char
。
p++; // works, because pointer is not constant
不,它起作用是因为这次它是一个指针(不是数组)。
*p = 'M'; // error, because string is constant
和上面一样,这又是一个char
,所以它能工作是因为它是正确的类型而不是因为字符串是“常量”。而且,正如 Michael Walz 在评论中所述,即使它可以编译,它也会在运行时产生未定义的行为(很可能是 segfault
崩溃),因为规范没有说明字符串是否指向by *p
是只读的还是不是(然而,似乎大多数现代编译器实现决定将其设为只读)。这可能会产生 segfault
。
有关详细信息,请参阅 this SO question .
关于c - 在字符串上使用指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46057088/