I’ve searched, but all I can find is where a function to reverse a string in place. Here’s what I have so far:
char* reverseString(char* string)
{
int i, j;
char reversed[sizeof(string)];
j = strlen(string);
for (i = strlen(string); i >= 0; i--)
{
reversed[j - i] = string[i];
}
return reversed;
}
However, that hits the issue of reversed being a local variable, so returning a pointer to it throws
warning: function returns address of local variable [enabled by default]
You can dynamically allocate memory for it:
In this case, the caller must remember to free() the allocated buffer that is returned.
Or you can have caller to pass in a buffer that’s large enough to hold the reversed string:
Note also that in your current code:
char reversed[sizeof(string)];is wrong,inside this function
stringis just achar*, sosizeof(string)gives you the size of achar*, not the length of the string this char* points to.