考虑这个定义:
char *pmessage = "now is the time";
Run Code Online (Sandbox Code Playgroud)
在我看来,pmessage将指向内存中包含这些字符的连续区域和最后一个字符'\0'.所以我从中得出,只要我在这个区域的范围内,我就可以使用指针算法来访问该字符串中的单个字符.
那么为什么他们说(K&R)修改个别角色是不确定的?
此外,为什么当我运行以下代码时,我得到一个"分段错误"?
*(pmessage + 1) = 'K';
Run Code Online (Sandbox Code Playgroud)
bra*_*ray 17
C中的字符串文字不可修改.字符串文字是在程序的源代码中定义的字符串.编译器经常将字符串文字存储在已编译二进制文件的只读部分中,因此实际上您的pmessage指针将进入您无法修改的区域.可以使用上面的语法修改存在于可修改内存中的缓冲区中的字符串.
尝试这样的事情.
const char* pmessage = "now is the time";
// Create a new buffer that is on the stack and copy the literal into it.
char buffer[64];
strcpy(buffer, pmessage);
// We can now modify this buffer
buffer[1] = 'K';
Run Code Online (Sandbox Code Playgroud)
如果您只想要一个可以修改的字符串,则可以避免使用具有以下语法的字符串文字.
char pmessage[] = "now is the time";
Run Code Online (Sandbox Code Playgroud)
此方法直接将字符串创建为堆栈上的数组,并可在适当位置进行修改.
字符串是常量,无法修改.如果要修改它,可以执行以下操作:
char pmessage[] = "now is the time";
Run Code Online (Sandbox Code Playgroud)
这会初始化一个字符数组(包括\ 0),而不是创建一个指向字符串常量的指针.