Sam*_*Sam 5 c string reverse segmentation-fault
我在C中提出了以下解决方案来反转字符串:
#include <stdio.h>
void reverse(char * head);
void main() {
char * s = "sample text";
reverse(s);
printf("%s", s);
}
void reverse(char * head) {
char * end = head;
char tmp;
if (!head || !(*head)) return;
while(*end) ++end;
--end;
while (head < end) {
tmp = *head;
*head++ = *end;
*end-- = tmp;
}
}
Run Code Online (Sandbox Code Playgroud)
但是我的解决方案是segfaulting.根据GDB,违规行如下:
*head++ = *end;
Run Code Online (Sandbox Code Playgroud)
在while循环的第一次迭代中,行segfaults.end指向字符串"t"的最后一个字符,head指向字符串的开头.那么为什么这不起作用呢?
Eri*_*rik 32
更改
char * s = "sample text";
Run Code Online (Sandbox Code Playgroud)
至
char s[] = "sample text";
Run Code Online (Sandbox Code Playgroud)
"示例文本"是一个字符串文字,可以驻留在地址空间的只读部分.使用数组语法可确保将此字符串复制到堆栈,这是可写的.
cod*_*ict 11
你s指向一个字符串文字:
char * s = "sample text";
Run Code Online (Sandbox Code Playgroud)
在函数中,reverse您尝试修改字符串文字,从而导致未定义的行为.
要解决此问题,请创建s一个char数组:
char s[] = "sample text";
Run Code Online (Sandbox Code Playgroud)