【发布时间】:2011-03-07 13:18:31
【问题描述】:
我在 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 指向字符串的开头。那么为什么这不起作用呢?
【问题讨论】:
-
\0 在字符串文字中是自动的
标签: c string segmentation-fault reverse