就地反转字符串用C [英] In-Place String Reverse in C

查看:148
本文介绍了就地反转字符串用C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想学C的基础知识,但我想不通为什么这个code不起作用。反向while循环()导致总线错误。我发现了一个编程采访本书作为一个有效的解决方案几乎相同code,但非此非彼其他类似的方法我已经看到张贴在这里没有一个总线错误为我工作。

 的#include<&stdio.h中GT;void反转(字符* STR){
 字符*结束= str中;
 焦炭TMP = 0;
 如果(STR){
  而(*完){
   结束++;
  }
   - 结束;
  而(完> STR){
   TMP = *结束;
   * end-- = *海峡;
   *海峡++ = tmp目录;
  }
 }
}诠释主(){
 字符* A =12;
 看跌(一);
 反向(一);
 看跌(一); 返回0;
}


解决方案

的问题是,你试图扭转不断的文本字符串,它是只读的。更改的声明 A 烧焦一个[​​] =12; ,使之成为可写的字符数组,而不是

I am trying to learn the fundamentals of C, but I cannot figure out why this code doesn't work. The while loop in reverse() causes a bus error. I found almost identical code in a programming interview book as a valid solution, but neither this nor other similar methods I have seen posted here work for me without a bus error.

#include <stdio.h>

void reverse(char* str) {
 char* end = str;
 char tmp = 0;
 if(str) {
  while(*end) {
   end++;
  }
  --end;
  while(end>str) {
   tmp = *end;
   *end-- = *str;
   *str++ = tmp;
  }
 }
}

int main() {
 char* a = "12";
 puts(a);
 reverse(a);
 puts(a);

 return 0;
}

解决方案

The problem is that you're trying to reverse a constant literal string, which is read only. Change the declaration of a in main to char a[] = "12"; to make it a writable char array instead

这篇关于就地反转字符串用C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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