以下代码在第2行接收seg错误:
char *str = "string";
str[0] = 'z'; // could be also written as *str = 'z'
printf("%s\n", str);
Run Code Online (Sandbox Code Playgroud)
虽然这非常有效:
char str[] = "string";
str[0] = 'z';
printf("%s\n", str);
Run Code Online (Sandbox Code Playgroud)
经过MSVC和GCC测试.
这是一个连接两个字符串的程序的简单示例.
#include <stdio.h>
void strcat(char *s, char *t);
void strcat(char *s, char *t) {
while (*s++ != '\0');
s--;
while ((*s++ = *t++) != '\0');
}
int main() {
char *s = "hello";
strcat(s, " world");
while (*s != '\0') {
putchar(*s++);
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我想知道为什么它有效.在main()中,我有一个指向字符串"hello"的指针.根据K&R的书,修改这样的字符串是未定义的行为.那么为什么程序能够通过追加"世界"来修改它呢?或者是否附加不被视为修改?