C 解决方案段错误中反转字符串
我在 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;
}
}
但是我的解决方案是段错误。根据 GDB 的说法,有问题的行如下:
*head++ = *end;
该行在 while 循环的第一次迭代时出现段错误。 end 指向字符串“t”的最后一个字符,head 指向字符串的开头。那么为什么这不起作用呢?
I've come up with the following solution in C for reversing a string:
#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;
}
}
However my solution is segfaulting. According to GDB, the offending line is the following:
*head++ = *end;
The line segfaults on the first iteration of the while loop. end points to the last character of the string "t" and head points to the beginning of the string. So why isn't this working?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
更改
为
“示例文本”是一个字符串文字,可能驻留在地址空间的只读部分。使用数组语法可确保将此字符串复制到可写的堆栈中。
Change
To
"sample text" is a string literal which may reside in a read-only section of your address space. Using the array syntax ensures this string is copied to stack, which is writable.
您的
s
指向字符串文字:在函数
reverse
中,您尝试修改字符串文字,这会导致未定义的行为。要解决此问题,请将
s
设为 char 数组:Your
s
is pointing to a string literal:In the function
reverse
you are trying to modify the string literal which results in undefined behavior.To fix this make
s
a char array: