Reputation: 182
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;
}
}
}
Upvotes: 0
Views: 54
Reputation: 4207
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.
Upvotes: 0
Reputation: 4463
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.
Upvotes: 0
Reputation: 38163
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*’
Upvotes: 2