StackPointer StackPointer - 1 month ago 16
C++ Question

Reverse String C++ using char array

I wrote a simple C++ program to reverse a string. I store a string in character array. To reverse a string I am using same character array and temp variable to swap the characters of an array.

#include<iostream>
#include<string>
using namespace std;

void reverseChar(char* str);

char str[50],rstr[50];
int i,n;

int main()
{
cout<<"Please Enter the String: ";
cin.getline(str,50);
reverseChar(str);
cout<<str;
return 0;
}

void reverseChar(char* str)
{
for(i=0;i<sizeof(str)/2;i++)
{
char temp=str[i];
str[i]=str[sizeof(str)-i-1];
str[sizeof(str)-i-1]=temp;
}
}


Now this method is not working and, I am getting the NULL String as result after the program execution.

So I want to know why I can't equate character array, why wouldn't this program work. And what is the solution or trick that I can use to make the same program work?

Answer

sizeof(str) does not do what you expect.

Given a char *str, sizeof(str) will not give you the length of that string. Instead, it will give you the number of bytes that a pointer occupies. You are probably looking for strlen() instead.

If we fixed that, we would have:

for(i=0;i<strlen(str)/2;i++)
{
    char temp=str[i];
    str[i]=str[strlen(str)-i-1];
    str[strlen(str)-i-1]=temp;
}

This is C++, use std::swap()

In C++, if you want to swap the contents of two variables, use std::swap instead of the temporary variable.

So instead of:

char temp=str[i];
str[i]=str[strlen(str)-i-1];
str[strlen(str)-i-1]=temp;

You would just write:

swap(str[i], str[sizeof(str) - i - 1]);

Note how much clearer that is.

You're using C++, just use std::reverse()

std::reverse(str, str + strlen(str));

Global variables

It's extremely poor practice to make variables global if they don't need to be. In particular, I'm referring to i about this.

Executive Summary

If I was to write this function, it would look like one of the two following implementations:

void reverseChar(char* str) {
    const size_t len = strlen(str);

    for(size_t i=0; i<len/2; i++)
        swap(str[i], str[len-i-1]);
}

void reverseChar(char* str) {
    std::reverse(str, str + strlen(str));
}

When tested, both of these produce dlrow olleh on an input of hello world.