在字符串上使用指针 [英] Use of pointers on strings
问题描述
我对在字符串上使用指针感到非常困惑.感觉就像他们遵循不同的规则.考虑以下代码
I am really confused about the use of pointers on strings. It feels like they obey different rules. Consider the following code
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
我也在书中遇到了以下代码
Also I came across the following code in a book
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
我不明白应该暗示什么
请帮助,我在其他任何地方都找不到任何信息
Please help, I can't find any info anywhere else
推荐答案
char *ptr;
ptr = "apple"; // shouldn't it be *ptr = "apple"
否,因为 * ptr
将是 char
.因此,您可以编写 * ptr ='a'
,但不能按照您的建议编写.
No, because *ptr
would be a char
. So, you may write *ptr = 'a'
but you can't write as you suggest.
printf("%s", ptr) // Why should I send the address instead of the value
因为C中的字符串,是一个以零结尾的字符序列( char
)的地址(空字符,又名 \ x0
).
Because a string in C, is the address of a sequence of characters (char
) terminated by zero (the null character aka \x0
).
char str[] = "Quest";
char *p = "Quest";
str++; // error, constant pointer can't change
否,指针可以完全改变,但是在这里, str
是一个数组(与作为指针略有不同).但是,因此,它不能处理指针算法.
No, a pointer can perfectly change, but here, str
is an array (which is slightly different from being a pointer). But, thus, it cannot deal with pointer arithmetic.
*str='Z'; // works, because pointer is not constant
不,因为 * str
应该是 char
.
p++; // works, because pointer is not constant
不,它有效,因为这一次,它是一个指针(而不是数组).
No, it works because, this time, this is a pointer (not an array).
*p = 'M'; // error, because string is constant
与上述相同,它又是一个 char
,因此之所以起作用是因为它是正确的类型,而不是因为字符串是'constant'.而且,正如迈克尔·沃尔兹(Michael Walz)在评论中指出的那样,即使它可以编译,它也会在运行时产生不确定的行为(很可能是 segfault
崩溃),因为该规范无法确定字符串是否指向通过 * p
设置是否为只读(但是,似乎大多数现代编译器实现都决定将其设置为只读).可能会产生 segfault
.
Same as above, this is a char
again, so it works because it is the right type and not because the string is 'constant'. And, as stated by Michael Walz in the comments, even though it might compile, it will produce an undefined behavior at runtime (most likely a crash with segfault
) because the specification do not tell if the string pointed by *p
is read-only or not (yet, it seems that most of the modern compilers implementation decide to make it in read-only). Which might produce a segfault
.
有关更多信息,请参考此SO问题.
For more information, refer to this SO question.
这篇关于在字符串上使用指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!