你能找到以下代码的错误吗?
int main(){
char *p="hai friends",*p1;
p1=p;
while(*p!='\0') ++*p++;
printf("%s %s",p,p1);
}
Run Code Online (Sandbox Code Playgroud)
我预计它将打印空格后跟一个字符串!
表达++*p++; 相当于;
++*p;
p++;
Run Code Online (Sandbox Code Playgroud)
++*p; 手段
*p = *p + 1;
Run Code Online (Sandbox Code Playgroud)
因为postfix的++优先级高于取消引用运算符*,所以它适用于*p.
并p指向一个常量字符串文字.在上面的操作中,您试图"在只读内存上写入" - 这是非法的 - 因此错误.
建议:
首先 - 声明一个可以修改的数组,不能更改字符串文字.
声明(阅读评论):
char string_array[] ="hai friends"; // notice `[]` in this declaration
// that makes `string_array` array
// to keep save original string do:
char p1[20]; // sufficient length // notice here `p1` is not pointer.
strcpy(p1, string_array) ;
char *p = string_array;
Run Code Online (Sandbox Code Playgroud)
现在您可以修改指针p和string_array[]数组内容.
| 归档时间: |
|
| 查看次数: |
211 次 |
| 最近记录: |