扭转℃溶液一个段错误字符串 [英] Reverse a string in C solution segfaulting

查看:113
本文介绍了扭转℃溶液一个段错误字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经想出了用C下述溶液逆转的字符串:

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;
  }
}

不过我的解决方案是段错误。据GDB,违规行为以下内容:

However my solution is segfaulting. According to GDB, the offending line is the following:

*head++ = *end;

的线出现segfaults在while循环的第一次迭代。结束点为字符串t和头指向的字符串的开头的最后一个字符。那么,为什么不是这个工作?

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?

推荐答案

修改

char * s = "sample text";

char s[] = "sample text";

示范文本是一个字符串文字可以驻留在一个只读的地址空间的部分。使用数组语法确保了这个字符串复制到堆栈,它是可写的。

"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.

这篇关于扭转℃溶液一个段错误字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆