char *output = calloc(strlen(input_string), sizeof(char));
and in main program:
char *reversed_string = sort_reverse("Whatever");
printf("%s\n", reversed_string);
//Remember to free reversed_string with
free(reversed_string);
//Since its allocated in the heap with calloc()
Try check man-page for calloc, it will zero out the bytes aswell, then you wont have to worry about setting the last element to '\0'.
NOTE: you have to iterate with "strlen(input_string) - 1" otherwise you will overwrite the needed '\0'
EDIT: As strlen excludes the '\0' in original string, then you have to make space for that by adding one to strlen return value so:
char *output = calloc(strlen(input_string) + 1, sizeof(char));
Source is my memory and I haven't looked it up so don't sue me.
Disclaimer: Just to be clear, it is definitely a good idea to add the terminator explicitly and I would not suggest leaving it off even if you know it is unnecessary. It makes verification easier and allows you to use the same algorithm for a truly uninitialized string. Also here you would likely run into problems if you try to call the function multiple times.
]]>In addition to the above corrections, you'll need to also set the null byte yourself on the ouput string:
output[strlen(str)] = '\0';
When i examined the program in gdb, the entire output array was already nulled. Is it reliable to expect it to be nulled every time?
]]> output[strlen(str)] = '\0';
Edit: too slow.
]]>for (i = strlen(str) - 1; i > -1; i--)
because string length in array goes from 0 to strlen(str) - 1, ommiting the NUL terminator. With your code you were copying the NUL character first, and that terminated the string before it even started.
Hmm, i thought strlen()'s code doesn't count the null character because:
size_t strlen(const char *str)
{
int i;
for (i = 0; str[i] != '\0'; i++) ;
return i;
}
the loop should've broke once it hits the '\0' and the i value not counting it.
The man page says that:
The strlen() function calculates the length of the string s, ***excluding the terminating null byte ('\0').***
It should do this though:
Hello\0 -> olleH\0
for (i = strlen(str) - 1; i > -1; i--)
because string length in array goes from 0 to strlen(str) - 1, ommiting the NUL terminator. With your code you were copying the NUL character first, and that terminated the string before it even started.
]]>#include <stdio.h>
#include <string.h>
Here are the global variables:
char output[999];
Here's the function to sort string to reverse order (I THINK THE PROBLEM IS HERE):
char output[999];
char *sort_reverse(const char *str)
{
int i, j = 0;
for (i = strlen(str); i > 0; i--)
{
output[j] = str[i];
j++;
}
return output;
}
And, function int main(void):
int main(void)
{
printf("Reverse of \"Hello\": %s\n", sort_reverse("Hello"));
return 0;
}
The output is:
Reverse of "Hello":
Why is that? how can i fix that?
]]>