ritratt
ritratt

Reputation: 1858

Why is the first character of this in place string reversal function not changing?

I wrote this small piece of code to reverse a string in place.

#include "template.h"

void main()     {
        char temp;
        char *str = NULL;
        int read, i;
        size_t len = 20;


        read = getline(&str, &len, stdin);
        if (read > -1)
        {
                str[strlen(str) - 1] = '\0';
                for (i = 0; i < strlen(str)/2; i++)
                {
                        temp = str[i];
                        str[i] = str[strlen(str) - i];
                        str[strlen(str) - i] = temp;
                }
        printf("%s\n", str);
        }
        else
                printf("FOFF!\n");
}

When I input abcdef the output is afedcb. Why is the first character not being shifted to the end?

Upvotes: 1

Views: 241

Answers (2)

CS Pei
CS Pei

Reputation: 11047

you have a bug in your code

str[i] = str[strlen(str) - i]; // should be str[i] = str[strlen(str) - i -1];

And

str[strlen(str) - i] = temp ; // should be str[strlen(str) - i - 1] = temp;

otherwise when i == 0, str[strlen(str) - 0] which is \0;

This is the fully working code

    #include "stdio.h"
    #include "string.h"


    int main()
    {
            char temp;
            char *str = NULL;
            int read, i;
            size_t len = 20;


            read = getline(&str, &len, stdin);
            if (read > -1)
            {
                    str[read - 1] = '\0';
                    for (i = 0; i < strlen(str)/2; i++)
                    {
                            temp = str[i];
                            str[i] = str[read - 1 - i - 1];
                            str[strlen(str) - i - 1] = temp;
                    }
                    printf("%s\n", str);
            }
            else
                    printf("FOFF!\n");
    }

Upvotes: 2

Madan Ram
Madan Ram

Reputation: 876

This is my code to reverse string.

void reverse(char str[],int len)
{
    char c;
    int i;
    int n=(len-1)/2;
    for(i=0;i<=n;i++)
    {
        c=str[len-i-1];
        str[len-i-1]=str[i];
        str[i]=c;
    }
}

Upvotes: 0

Related Questions