Gau*_*ant 4 c c-strings char-pointer
我真的很困惑在字符串上使用指针.感觉他们遵守不同的规则.请考虑以下代码
char *ptr = "apple";// perfectly valid here not when declaring afterwards like next
ptr = "apple"; // shouldn't it be *ptr = "apple"
Run Code Online (Sandbox Code Playgroud)也printf()表现不同-
printf("%s", ptr) // Why should I send the address instead of the value
Run Code Online (Sandbox Code Playgroud)我还在一本书中看到了以下代码
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
Run Code Online (Sandbox Code Playgroud)我无法理解应该暗示什么
请帮忙,我在其他地方找不到任何信息
char *ptr;
ptr = "apple"; // shouldn't it be *ptr = "apple"
Run Code Online (Sandbox Code Playgroud)
不,因为*ptr会是一个char.所以,你可以写,*ptr = 'a'但你不能按照你的建议写.
printf("%s", ptr) // Why should I send the address instead of the value
Run Code Online (Sandbox Code Playgroud)
因为C中的字符串char是以零结尾的字符序列()的地址(也称为空字符\x0).
char str[] = "Quest";
char *p = "Quest";
str++; // error, constant pointer can't change
Run Code Online (Sandbox Code Playgroud)
不,指针可以完美地改变,但这里str是一个数组(与指针略有不同).但是,因此,它无法处理指针运算.
*str='Z'; // works, because pointer is not constant
Run Code Online (Sandbox Code Playgroud)
不,它有效,因为*str应该是一个char.
p++; // works, because pointer is not constant
Run Code Online (Sandbox Code Playgroud)
不,它有效,因为这次是指针(不是数组).
*p = 'M'; // error, because string is constant
Run Code Online (Sandbox Code Playgroud)
与上面相同,这是一个char,所以它起作用,因为它是正确的类型而不是因为字符串是'常量'.并且,正如Michael Walz在评论中所述,即使它可能编译,它也会在运行时产生未定义的行为(很可能是崩溃segfault),因为规范不会告诉指向的字符串*p是否为只读(然而,似乎大多数现代编译器实现决定以只读方式实现它.哪个可能产生一个segfault.
有关更多信息,请参阅此SO问题.
| 归档时间: |
|
| 查看次数: |
329 次 |
| 最近记录: |