TAZO
TAZO

Reputation: 33

Swap 2 char of a C++ array

I have a problem with memory access. When i = 0, Visual Studio throws an exception with reference to a line as labelled in the following code.

Can't access at 0x00AD8B3B and 0x00AD8B3B equals scr+np-i

How can I fix the for-loop body so as to fix this issue?

int o_strrev(char* scr)
{
  int np = strlen(scr) - 1;
  char tmp;

  if (!scr) return -1;
  if (!*scr) return -1;

  for (int i = 0; i < np / 2; i++)
  {
    tmp = scr[np-i];
    scr[np-i] = scr[i]; # this line
    scr[i] = tmp;
  }

  return 0;
}

Upvotes: 3

Views: 3365

Answers (3)

Paul Evans
Paul Evans

Reputation: 27577

You're most likely calling o_strrev with a string literal, some thing like:

o_strrev("This ain't gonna work!");

This will compile with most compilers and at most generate a warning. Try cranking up your warning level.

Instead, you want to make a dynamic copy of your string on the heap and work with a char* pointer to that, something like:

string str = "This is gonna work!!"
size_t len = str.size();
char* my_string = new char[len + 1];
strncpy(my_string, str.data(), len)
my_string[len] = '\0';

o_strrev(my_string);

// ...

delete[] my_string;

Upvotes: 1

swinefish
swinefish

Reputation: 561

As pointed out by @Revolver_Ocelot, you are probably passing a const char* from a string literal. Since these are, by definition, constant, you can't modify them in the way you're trying to. You need some way to convert const char* into a non constant char*. Something along these lines will work for you:

string str = "string";
char* cstr = new char[str.length() + 1];
strcpy(cstr, str.c_str());

I've compiled your code in g++ using non constant char* and it works fine. Just remember to deallocate your char* when you're done with it. We don't want memory leaks ;)

Upvotes: 2

JCDenton
JCDenton

Reputation: 151

I see you are trying to reverse a string. Might I suggest a simpler way

void reverse(char *string_var) 
{
    int length, c;
    char *begin, *end, temp;

    length = strlen(string_var);
    begin  = string_var;
    end    = string_var;

    for (c = 0; c < length - 1; c++)
       end++;

    for (c = 0; c < length/2; c++)
    {        
        temp   = *end;
        *end   = *begin;
        *begin = temp;

        begin++;
        end--;
   }
}

Make sure you pass character array of the form

char word[64]

Or maybe by recursion

void reverse(char *x, int begin, int end)
{
   char c;

   if (begin >= end)
      return;

   c = *(x+begin);
   *(x+begin) = *(x+end);
   *(x+end) = c;

   reverse(x, ++begin, --end);
 }

Upvotes: 1

Related Questions