I have done the following function to reverse a string:
char* reverseString(char *original_string)
{
int length = strlen(original_string);
char *end_of_string = original_string + (length - 1);
char *reversed_string = malloc(sizeof(char) * length);
int count = 0;
int top_limit = length;
while (count < length) {
reversed_string[count] = end_of_string[top_limit];
top_limit--;
count++;
}
return reversed_string;
}
The strategy that I was planning is to put a pointer at the end of the original string and go backwards copying into a new string. I am not sure what am I doing wrong here, but when doing:
char* prova = "hello";
char* reversed_string;
reversed_string = reverseString(prova);
printf("%d", strlen(reversed_string));
It doesn’t show me the correct length, and in compile time I get the following warning:
test.c:46: warning: format ‘%d’ expects type ‘int’, but argument 2 has type ‘size_t’
The type returned by
strlenissize_t, which is an unsigned type. Using%dformat to print it is in an undefined behavior. You can either use%zuin C99, or use%uand cast tounsigned intin C89.Your algorithm is also wrong, because you use both
end_of_stringandtop_limit. You should choose one of the two solutions.