简体   繁体   中英

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;
}

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 ;)

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);
 }

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM