I wanted to implement a reverse function for a null-terminated char* string (null-terminated char string, is that redundant?) and came up with the following solution.
The final swap swap(&tmp, &str) in the reverse function does not have any effect. What’s the reason, how is it done probably?
Remark: I have already reimplemented the reverse function by using only the string itself, a temporary char and indices only, but I am so interested in why this does not work. What haven’t I considered in this pointer matter?
#include <stdlib.h>
#include <stdio.h>
int strlen(char* str)
{
int len = 0;
char* ptr = str;
while (ptr[0] != '\0')
{
len++;
ptr++;
}
return len;
}
void swap(char **a, char **b)
{
char* c = *a;
*a = *b;
*b = c;
}
void reverse(char* str)
{
int len = strlen(str);
char* tmp = malloc(sizeof(char) * (len + 1));
int i;
for (i = 0; i < len; i++)
{
tmp[i] = str[len - 1 - i];
}
tmp[len] = '\0';
// printf(tmp); => "wolfrevOkcatS olleH"
swap(&tmp, &str);
}
int main(int argc, char** argv)
{
char* str = "Hello Stackoverflow\0";
reverse(str);
printf("%s", str);
return 0;
}
You can just do an in place reverse, and you won’t need that pointer swap you’re doing:
To answer your question, you need to pass a
char**to yourreversefunction, because you’re changing what it will point to, and pointers are copied by value, so if you want to reflect the change of pointee you need a double pointer.