本文介绍了反转字符串递归并使用循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我曾尝试编写以两种方式反转字符串的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; }推荐答案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.引用:我试过编写一个以两种方式反转字符串的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. 这篇关于反转字符串递归并使用循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-15 04:31