反转字符串递归并使用循环 [英] Reverse a string recursive and using loops

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

问题描述

我曾尝试编写以两种方式反转字符串的ac程序。



第二种方式应该是recursiv。

我的函数putBack使用malloc为结果动态分配内存。

我在哪里可以释放内存?我认为putBack()返回的指针中的数据已经被复制到新的缓冲区中了性格更大。但我不知道怎么做。



我尝试过:



I have tried to write a c programm that reverse a string in two way .

Second way should be recursiv .
my function putBack uses malloc to dynamically allocate the memory for the result .
where can I free the memory?I think exactly when the data from the pointer returned by putBack() has already been copied into the new buffer one character larger.But I don't know how.

What I have tried:

#include <stdio.h>
#include <stdlib.h>

//1
  char *reverse(char *s){
		int lengths = length(s);
	char *reverse = (char *) malloc(sizeof(char) * lengths);
	if(lengths>0){
		int k = lengths-1;
		for(int i=0; i<lengths; i++, k--){
			reverse[i] = s[k];
		}
	}else{
		reverse = "";
	}
	return reverse;;
}

int length(char *s) {
  int n = 0;
  while(*s != '\0') {
    n++;
    s++;
  }

  return n;
}


void copy(char* s, int n, char* t) {
  int i = 0;
  while(i < n) {
    t[i] = s[i];
    i++;
  }
}


char* putBack(char* s, char c) {
  const int n =  length(s);
 
 char* r = malloc(sizeof(char) * (n+2));
  copy(s, n, r);
  r[n] = c;
  r[n+1] = '\0';
 return r;
}


char* reverseRec(char *input){
     static int i =0; 
     static char ReverseStr[10];

     char* R[length(input)];

     if(*input){
        reverseRec(input+1);
        ReverseStr[i++]= *input;

        *R =putBack(ReverseStr,*input); //hängt ein Zeichen hinten  String an

     }
     printf("%c", *input);

     return *R;
   }

推荐答案

为什么你会尝试递归地反转字符串?这是一种非常低效的方式......

但是......这很简单。

它有一种非常强烈的作业气味,所以我'我不打算给你任何真正的代码。

写一个接受两个参数的函数,两个指向字符的指针:

Why would you even try to reverse a string recursively? It's a very inefficient way to do it...
But ... it's pretty simple.
This has a very strong "homework" smell to it, so I'm not going to give you any "real" code.
write a function that accepts two parameters, both pointers to character:
void Reverse(char* in, char* out)



函数内部比较进出:


Inside the function compare in and out:

in < out      swap characters between in and out, call Reverse with in + 1 and out - 1.
in == out     )
               --- do nothing.
in > out      )

明白我的意思?简单。但非常非常低效 - 循环更简单,更容易使用。

See what I mean? Simple. But very, very inefficient - a loop is much simpler and easier to work with.


考虑这个代码审查。

首先帮我们一个忙;在发布之前,请确保代码可以编译。除非问题是无法编译。



反向()功能:

1.更改< b> char * reverse(char * s)到 char * reverse(const char * s)

2. length()函数未定义(将导致编译错误)。声明原型或将定义移到 reverse()函数之上。

3. length()等同于标准C-函数 strlen()。此函数不包括结果中的'\ 0'。因此,您分配的缓冲区大小必须长度+ 1 字符大小 - 不是长度

4.检查返回的指针< b>的malloc()的。如果 malloc()失败,那么如果长度>则程序会爆炸0

5.不再使用i ++编写增量,而是使用++ i。是的我知道现在每个人都这样做,但是有正当理由认为这是一个坏习惯。

6.要么返回指向已分配内存的指针,要么返回null。不要将反向指针分配给静态字符串(反向=),否则你的程序会在某个时刻爆炸。



复制功能:

1.从技术上讲,如果您提供传递给 copy()的两个字符串缓冲区的长度,或者更安全再次你可能有问题。



putBack 功能:

1.这会分配一个任意缓冲区,这可能是永远不会被释放。我建议你重新考虑这个,否则你会在整个地方泄漏记忆。



reverseRec 功能:

此函数表明您不了解递归的工作原理。恐怕我没有时间告诉你这个功能的所有问题。

1.可以避免静态变量。另外,在某些时候你会有 ReverseStr 的缓冲区溢出。

2. R [长度(输入)] 语法无效,不会编译。

3. * R = putBack(ReverseStr,*输入); 将不断泄漏内存(参见 putBack

4.如果需要静态值,则必须在某些时候将它们设置回原始值。 只会在每次通话时递增,直到程序因缓冲区溢出而爆炸。



打破铅笔和纸张并锻炼发生了什么,然后弄清楚你需要做些什么来修复它。 C编码没有神奇之处,你实际上必须知道事情是如何工作的 - 使用逻辑而不是猜测工作。
Consider this a code review.
First do us a favor; before posting, please ensure that the code can compile. Unless the question is about being unable to compile.

reverse() function:
1. Change char *reverse(char *s) to char *reverse(const char *s).
2. The length() function is undefined (will cause compilation error). Either declare a prototype or move the definition above the reverse() function.
3. The length() is equivalent to the standard C-function strlen(). This function does not include the '\0' in the result. Therefore, the buffer size you are allocating must be lengths + 1 characters in size - not lengths.
4. Check the pointer returned bay malloc(). If malloc() fails, then the program will blow up if lengths > 0.
5. Get out of the habit of writing increments as i++, use ++i instead. Yes I know that everyone does it that way now day, but there are legitimate reasons for it being a bad habit.
6. Either return a pointer to the allocated memory or null. Do not assign the reverse pointer to at static string (reverse = "") or your program will just blow up at some point.

copy function:
1. Technically it would be safer if you provided the lengths of both string buffers that are being passed to copy() or again you may have issues.

putBack function:
1. This allocates an arbitrary buffer, which may never get freed. I recommend you rethink this or you will be leaking memory all over the place.

reverseRec function:
This function shows that you do not understand how recursion works. I am afraid I do not have the time to tell you everything that is wrong with this function.
1. Static variables can be avoided. Plus you will have a buffer overrun of ReverseStr at some point.
2. R[length(input)] is invalid syntax and will not compile.
3. *R = putBack(ReverseStr, *input); will be constantly leaking memory (See putBack)
4. If static values were required, then they must be set back to their original values at some point. i is just going to increment on each call until the program blows up due to buffer overrun.

Break out the pencil and paper and workout what is going on, then figure out what you need to do to fix it. There is no magic in C-coding, you actually have to know how things work - use logic not guess work.


引用:

我试过编写一个以两种方式反转字符串的ac程序。

第二种方式应该是recursiv。

I have tried to write a c programm that reverse a string in two way .
Second way should be recursiv .



整个使用递归来反转字符串的想法很糟糕。这会使事情变得缓慢,复杂,这会滥用调用堆栈只是为了获得乐趣。

要使用递归,最好有一个很好的理由:

- 数据本质上是递归的:二叉树,语言解析。

- 使用递归定义轻松编写代码:GCD函数,Fibonacci套件。



否则你可以自由地做一些你想要的复杂事情,但不要指望我们这样跟着你。


The whole idea of using recursion to reverse a string is bad. It is making things slow, complicated and this will abuse calling stack just for the pleasure.
To use recursion, it is better to have a good reason:
- The data is recursive by nature: a binary tree, language parsing.
- Using the recursive definition ease writing code: GCD function, Fibonacci suite.

Otherwise you are free to do things as complicated as you want, but do not expect us to follow you on this way.


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

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