本文介绍了反转c中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试原地反转字符串.
Im trying to reverse a string in place.
void reverseStr(char *str)
{
int i;
int length;
int last_pos;
length = strlen(str);
last_pos = length-1;
for(i = 0; i < length / 2; i++)
{
char tmp = str[i];
str[i] = str[last_pos - i];
str[last_pos - i] = tmp;
}
}
Program received signal SIGSEGV, Segmentation fault.
0x0000000000400893 in reverseStr (str=0x400974 "Haus") at main.c:102
102 str[i] = str[last_pos - i];
(gdb) print i
$1 = 0
(gdb) print last_pos
$2 = 3
(gdb) print str
$3 = 0x400974 "Haus"
(gdb) print str[3]
$4 = 115 's'
感谢您的阅读.我不明白,这个指令怎么会导致错误?问候:)
Thank you for reading.I dont get it, how can this instruction cause an error? Regards :)
推荐答案
reverseStr
中的代码没问题,问题出在调用代码上.您几乎可以肯定将字符串文字或其他一些只读内存传递给函数.
The code in reverseStr
is fine, the problem is in the calling code. You almost certainly are passing a string literal or some other read-only memory to the function.
很可能您的调用代码是:
Most likely your calling code is:
char *str = "my string";//str points to a literal which cannot be modified
reverseStr(str);
但是你需要传递可写内存.像这样:
But you need to pass writeable memory. Like this:
char str[] = "my string";
reverseStr(str);
这篇关于反转c中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!