Invert string in C

4

I'm trying to invert a string into C but the function is cleaning it:

for(i = 0; i < (int)(size/2); i++)
{
   tmp = buffer[i]; //armazena o character inicial
   buffer[i] = buffer[size - i]; //Troca o character da ponta oposta
   buffer[size - i] = tmp; //Armazena o character inicial no buffer
}

Why do you clean the string when I re-strlen this string?

The Hello string has 5 characters, so the size variable will have the value 5. ~ changing the values in the above code:

  • tmp = buffer [0] (or the 'H' character)
  • buffer [i] = buffer [size - i] (the position where the character H was now has the character value of the position [5 - 0], ie the position 5, which corresponds to the character 'o' )
  • buffer [size - i] = tmp (as tmp had the value of the character already buffered [i], then the position of character 'o' will have the value of character 'H')

Is this analysis correct? What's the problem?

    
asked by anonymous 01.07.2016 / 20:27

3 answers

8

The problem is that "size - i" will get a character in addition to the length of the string. For example, a string with size 5 will have characters in s [0], s [1], s [2], s [3] is [4], but s [5] will be the character \ 0. Once this character is played in s [0], the string will appear to have zero length from then on, although it still occupies six memory locations.

In my view the program should be fixed to buffer [size - i - 1]. I think (int) in size / 2 is also unnecessary if size is of integer type, because in C an integer division always returns an integer rounded down.

    
01.07.2016 / 20:34
5

The biggest problem is that you are forgetting to remove 1 in the final position.

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

int main(void) {
    char buffer[] = "Hello";
    size_t size = strlen(buffer);
    for(int i = 0; i < size / 2; i++) {
       char tmp = buffer[i]; //armazena o character inicial
       buffer[i] = buffer[size - i - 1]; //Troca o character da ponta oposta
       buffer[size - i - 1] = tmp; //Armazena o character inicial no buffer
    }
    printf("%s", buffer);
    return 0;
}

See working on ideone and on CodingGround .

    
01.07.2016 / 20:36
0

Here is a solution (tested) for the proposed problem:

/* reverse.c */

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

char * reverse( char * s )
{
    int length = strlen(s) ;
    int c, i, j;

    for (i = 0, j = length - 1; i < j; i++, j--)
    {
        c = s[i];
        s[i] = s[j];
        s[j] = c;
    }

    return s;
}


int main( void )
{
    char str[] = "Ola Mundo!";

    printf("%s\n", reverse(str) );

    return 0;
}

/* fim-de-arquivo */
    
21.07.2016 / 22:38