无法修改 char* - 内存访问冲突 [英] can't modify char* - Memory access violation
本文介绍了无法修改 char* - 内存访问冲突的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么显示内存访问冲突"?
Why does it say "Memory access violation"?
char* str = "HelloGuys";
int len = strlen(str);
for (int i=0; i<(len/2); ++i){
char t = str[len-i-1];
str[len-i-1] = str[i]; //error
str[i] = t;
}
推荐答案
字符串文字存储在内存的只读部分.任何修改字符串文字内容的尝试都会调用未定义行为(大多数实现中的分段错误).
String literals are stored in read only section of memory. Any attempt to modify the contents of a string literal invokes Undefined Behaviour (segmentation fault on most implementations).
改为使用字符数组
char str[] = "HelloGuys";
这篇关于无法修改 char* - 内存访问冲突的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文