Josh Lake
Josh Lake

Reputation: 607

Am I missing something in my function?

This is what I have so far and I keep getting an error. Any help?

void ReverseString(char* string) {
    int len = strlen(string);
    for(int i = 0; i < len; i++)
    {
         string[i] = string[len-i];
    }
}

Upvotes: 2

Views: 127

Answers (5)

ThomasMcLeod
ThomasMcLeod

Reputation: 7769

should be string[i] = string[len-i-1];

// added (untested):  

void ReverseString(char * string) {   
    int len = strlen(string);  
    for(int i = 0; i < len / 2; i++)  
    {  
         string[i] ^= string[len-i-1];  
         string[len-i-1] ^= string[i];  
         string[i] ^= string[len-i-1];  
    }  
} 

Upvotes: 0

Nim
Nim

Reputation: 33645

This is tagged C++, do it the C++ way...

std::string ReverseString(std::string str) 
{
  std::reverse(str.begin(), str.end());
  return str;
}

Upvotes: 1

codaddict
codaddict

Reputation: 455192

  • When i is 0 you'll be accessing string[len] which is incorrect as the valid index in an array of length len are [0,len-1]

If I understand you intent correctly you are trying to reverse the string but I can see a few things missing:

  • You are not swapping.
  • Also the swapping should happen for one half of the array, not for the entire array.

The following snippet fixes these issues:

int len = strlen(string);
for(int i = 0; i < len/2; i++) {
    swap(string[len-i-1],string[i]);
}

Upvotes: 6

ruslik
ruslik

Reputation: 14890

Besides two already mentioned errors:

You'll make a palindrom out of the original string. The first half will became equal to second half inversed. However, the second half will remain the same. This is not what the function name declares.

Upvotes: 1

Secko
Secko

Reputation: 7716

First of all, you would get an error on line 6.

Change the { into }. Then try again.

Upvotes: 2

Related Questions