简体   繁体   中英

How to make sure function call proper with pointer

Below code will work when I call like this:

char arr[] = "foobar";
reverse(arr);

but it won't work when I call like this as it is pointing to read only portion

 char*a = "foobar";
 reverse(a);

Now my question is that is there any way I can avoid user to call like this?

void reverse(char *str)
{
  char * end = str;
  char tmp;
  if (str) 
  { 
     while (*end)
     {      
       ++end;
     }
     --end;
     while (str < end)
     {
        tmp = *str;
        *str++ = *end;
        *end-- = tmp;
     }
  }

}

char arr[] = "foobar";

is array of char s, containing these chars: f , o , o , b , a , r , \\0 . While

char* a = "foobar";

is wrong. "foobar" here is a string literal, and this statement must be

 const char* a = "foobar"; // note the const

You cannot change string literals.

That is a common mistake - make difference between a pointer and an array.


And no, there's no way to prevent the user to call reverse with a string literal. The "user" is responsible for their actions.

If a is defined as it must be (using const ), the compiler will tell "the user" something like invalid conversion from 'const char*' to 'char*'

No, there is no way to guarantee that pointer being passed to function is valid. It is impressibility of caller to provide valid data. You can even do something like this

  int i = 0xABCD;
  reverse((char*) i);

Which doesn't make much sense but there is no way to check for such things in reverse.

Use a std::string . Foregoing any corruption, a std::string is a continuous block of memory with a known size.

You can even use std::reverse .

Besides with the correct settings, compilers will prevent you from assigning a string literal to a char* variable.

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