I have seen this code:
void reverse_string(char *str)
{
/* skip null */
if (str == 0)
{
return;
}
/* skip empty string */
if (*str == 0)
{
return;
}
/* get range */
char *start = str;
char *end = start + strlen(str) - 1; /* -1 for \0 */
char temp;
/* reverse */
while (end > start)
{
/* swap */
temp = *start;
*start = *end;
*end = temp;
/* move */
++start;
--end;
}
}
And I don’t understand why a pointer to a pointer is not passed in the function. How can it be reversed then, if a copy of the passed pointer is made inside the function? How are the changes being propagated outside?
It works because you’re making changes in the memory pointed by that pointer. So after the function ends the pointer still points where it used to, but the contents (the order of the characters) has changed. In other words, there’s no need to change the address
strpoints to.