Click here to Skip to main content
15,890,609 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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:

C++
#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;
   }
Posted
Updated 16-May-19 10:05am
v2

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:
C++
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.
 
Share this answer
 
Comments
Member 14076805 15-May-19 12:02pm    
I thought is easier, when i use free or delete to free the memory
OriginalGriff 15-May-19 12:14pm    
Why? First off how is that easier? And secondly how much memory are you going to create in order to reverse a 1MB string?

Thirdly, when are you going to free the memory? You can't free it at the end of the function because this is recursive and will need them to return to "lower levels".
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.
 
Share this answer
 
Quote:
I have tried to write a c programm that reverse a string in two way .
Second way should be recursiv .

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.
 
Share this answer
 
Comments
CPallini 17-May-19 3:51am    
The third good reason coul be homework. Have my 5.
Patrice T 17-May-19 4:08am    
Good one :)
Thank you

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900