可能重复:
为什么在写入字符串时会出现分段错误?
以下简单函数应该反转字符数组.
void reverse(char* str)
{
char* last = str;
// find end of the string
while(*last) {
++last;
}
// swap characters until the pointers meet in the middle
while(str < last)
{
--last;
char temp = *str;
*str = *last;
*last = temp;
++str;
}
}
int main()
{
char* a= "Hello";
reverse(a);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
代码编译.但它会引发有关访问冲突的运行时错误.根据调试器,罪魁祸首是以下行:
char temp = *str;
Run Code Online (Sandbox Code Playgroud)
任何想法为什么会发生?
char* a= "Hello";
Run Code Online (Sandbox Code Playgroud)
指针a指向字符串文字.根据该标准,尝试修改字符串文字会导致未定义的行为.在实现的情况下,分段错误表明编译器选择将字符串文字放在不可修改的内存中.
声明a为可修改的字符串.例如,像这样:
char a[] = "Hello";
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
716 次 |
| 最近记录: |