Function to invert a string

Asked

Viewed 2,153 times

1

I tried to do a function in order to invert a string but the program always returns (null).

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

char reverse(char string[])
{
   int length, i;

   length = strlen(string);

   char reverse_string[length];

   for(i=0; i<length; i++)
   {
      reverse_string[i] = string[(length - i) - 1];
   }

   return reverse_string;
}

int main()
{
   char string[50];

   gets(string);

   printf("%s", reverse(string));

   return 0;
}

I thought I might be putting the character ' 0' in the first position of reverse_string, but I added the "-1" in the operation and even then the program always returns (null). If anyone knows what’s going on and can give a hint, I’d appreciate it!

4 answers

3

The problem is that your function returns a char but reverse_string is a vector, the correct would be to return char*. Also, you forgot to mark the end of the converted string with the null terminator '\0'.

char* reverse(const char string[])
{
    int length, i;
    length = strlen(string);
    char *reverse_string = malloc(length + 1); // +1 para o terminador nulo

    for(i = 0; i < length; i++)
    {
        reverse_string[i] = string[(length - i) - 1];
    }
    reverse_string[length] = '\0'; //terminador nulo no fim da string
    return reverse_string;
}

Note that reverse_string has to be dynamically allocated. Otherwise you would be returning the address to a vector that has already been destroyed. And don’t forget you have to release your memory.

int main() { 
    char string[50];

    gets(string);
    char* reversed = reverse(string);
    printf(reversed);
    free(reversed); //libertar a memória
    return 0;
}

3

There are several problems in the code presented:

  • The function return type reverse() is char. If you want to return a string has to be char*.
  • A string reverse_string[] is allocated to the stack within the function reverse(), so the string will not survive the completion of the execution function. The return value of reverse() will be a pointer invalid.
  • The function strlen() calculates the size of the string without including the terminator '\0'. It is necessary to add the '\0' after the last character.

Two alternatives for implementation would be:

  1. Allocate the string to the heap, using malloc() and return the pointer to the string. In doing this, the string survives beyond the scope function and must then be released using free().
  2. Add a parameter to the function reverse() and move to this parameter a string already allocated to receive the inverted string. In this case the string to be passed as parameter can be allocated normally in the pile inside the main().

Following the implementation of these two variants, reverse_1() and reverse_2():

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

char* reverse_1(char string[])
{
  // armazena o tamanho da string sem o terminador '\0'
  int length = strlen(string);

  // aloca espaço no heap
  char* reverse_string = malloc((length + 1) * sizeof(char));

  // inverte a string
  for(int i = 0; i < length; i++)
       reverse_string[i] = string[length - i - 1];

  // coloca o terminador '\0'
  reverse_string[length] = '\0';

  return reverse_string;
}

void reverse_2(char string[], char reverse_string[])
{
  // armazena o tamanho da string sem o terminador '\0'
  int length = strlen(string);

  // inverte a string
  for(int i = 0; i < length; i++)
       reverse_string[i] = string[length - i - 1];

  // coloca o terminador '\0'
  reverse_string[length] = '\0';
}

int main()
{
  char s[50];
  gets(s);

  // teste de reverse_1
  char* rs1 = reverse_1(s);
  printf("reverse_1: %s\n", rs1);
  free(rs1);

  // teste de reverse_2
  char rs2[50];
  reverse_2(s, rs2);
  printf("reverse_2: %s\n", rs2);

  return 0;
}

0

You can invert a string inplace without making use of any standard library function, making use of only of pointer arithmetic, look at you:

void reverse( char str[] )
{
    char * ptr = str;

    while( ptr && *ptr )
        ptr++;

    for( ptr--; str < ptr; str++, ptr-- )
    {
        *str = *str ^ *ptr;
        *ptr = *str ^ *ptr;
        *str = *str ^ *ptr;
    }
}

Testing:

#include <stdio.h>  /* printf() */


void reverse( char str[] )
{
    char * ptr = str;

    while( ptr && *ptr )
        ptr++;

    for( ptr--; str < ptr; str++, ptr-- )
    {
        *str = *str ^ *ptr;
        *ptr = *str ^ *ptr;
        *str = *str ^ *ptr;
    }
}


int main( void )
{
    char txt[] = "O rato roeu a roupa do rei de Roma";

    reverse( txt );

    printf("%s\n", txt );

    return 0;
}

Exit:

amoR ed ier od apuor a ueor otar O

See working from Ideone

-2

good morning,

Example of a function to invert a string:

            string novaStr=string.Empty;
            string strOriginal;
            int i;

            strOriginal = "TesteInverter";

            for (i = strOriginal.Length-1; i >=0; i--)
            {
                novaStr += strOriginal[i];
            }

            Console.WriteLine(novaStr);
  • 5

    Ricardo, your answer does not help to solve the question specific problem and yet posted a code in another language, try to give a more direct answer to the question problem

Browser other questions tagged

You are not signed in. Login or sign up in order to post.