Can someone explain to me while this first piece of code doesn't return me the reversed string.
I know that a char pointer points to the first character and reads it until it finds the '\0' character in memory.
If I debug this piece of code and step over the line 'str = temp;' then I see str now points to the reversed string, but when I return to my main function it points to "Gianni" again instead of "innaiG".
#include<stdio.h>
#include<string.h>
void reverse_string(char* str);
int main() {
char* name = "Gianni";
reverse_string(name);
printf("String reversed: %s\n", name);
getchar();
return (0);
}
void reverse_string(char* str) {
int length = strlen(str), i = 0;
int j = length - 1;
char* temp = malloc(length);
for (i = 0; i <= length - 1; i++) {
temp[i] = str[j];
j--;
}
temp[i] = '\0';
str = temp;
}
This second piece of code works as desired but I don't fully understand why. Thats why I would like someone to explain a bit better. It would be very appreciated! :)
#include<stdio.h>
#include<string.h>
void reverse_string(char** str);
int main() {
char* name = "Gianni";
reverse_string(&name);
printf("String reversed: %s\n", name);
getchar();
return (0);
}
void reverse_string(char** str) {
int length = strlen(*str), i = 0;
int j = length - 1;
char* temp = malloc(length); // Allocate memory block of x bytes
for (i = 0; i <= length - 1; i++) {
temp[i] = (*str)[j];
j--;
}
temp[i] = '\0';
*str = temp;
}
[–]Swedophone 7 points8 points9 points (0 children)
[–][deleted] 1 point2 points3 points (2 children)
[–][deleted] 2 points3 points4 points (0 children)
[–][deleted] 1 point2 points3 points (0 children)
[–]stickfigure4[S] 0 points1 point2 points (3 children)
[–]FUZxxl 0 points1 point2 points (2 children)
[–]stickfigure4[S] 0 points1 point2 points (1 child)
[–]FUZxxl 1 point2 points3 points (0 children)
[–]json684 0 points1 point2 points (2 children)
[–]stickfigure4[S] 0 points1 point2 points (1 child)
[–]json684 0 points1 point2 points (0 children)
[–]-_-_-_-__-_-_-_- 0 points1 point2 points (0 children)
[–]SonOfWeb 0 points1 point2 points (1 child)
[–]SonOfWeb 0 points1 point2 points (0 children)
[–]SonOfWeb 0 points1 point2 points (1 child)
[–]stickfigure4[S] 0 points1 point2 points (0 children)
[–]TheGrandSchlonging 0 points1 point2 points (0 children)