为什么这个code产生分段错误? [英] Why does this code produce a segmentation fault?
本文介绍了为什么这个code产生分段错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在第18行,我得到的第一个迭代赛格故障(I = 0)。
On line 18, I get a seg fault in the first iteration (i = 0).
#include <stdio.h>
int main(void) {
char* str = "mono";
int length = 0;
int i;
for (i = 0; ; i++) {
if (str[i] == '\0') {
break;
} else {
length++;
}
}
for (i = 0; i < length / 2; i++) {
char temp = str[length - i - 1];
str[length - i - 1] = str[i]; // line 18
str[i] = temp;
}
printf("%s", str);
return 0;
}
我写这个算法,扭转一个字符串。
I wrote this algorithm to reverse a string.
推荐答案
您正在修改一个字符串:
You are modifying a string literal:
char* str = "mono";
和字符串文字是用C不可修改的。
and string literals are non-modifiable in C.
要解决您的问题,可使用由字符串初始化数组:
To fix your issue, use an an array initialized by the string literal:
char str[] = "mono";
这篇关于为什么这个code产生分段错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文