I'm recently writing a function to reverse a string input. For example, input = "hello", then output = "olleh" I got a question, when I return the address of char*, it looks fine, but why I cannot print the string of that pointer ?
many thanks at first and here is my code :
#include <stdlib.h>
#include <stdio.h>
char* reverseString(char*);
int main(void)
{
char* s = "hello";
char* out;
out = reverseString(s);
printf("%p %s\n", out, out);
return 0;
}
char* reverseString(char* s)
{
int i;
int size;
char* reverse;
size = sizeof(s);
char reversechar[size];
for (i = 1; i < size + 1; i++)
reversechar[i - 1] = s[size - i];
reverse = reversechar;
//printf("%p\n",reverse);
return reverse;
}
result : 0x7fff40db7300 @@
reversepoints to memory on the stack, being valid only insidereverseString. The momentreverseStringreturned this memory had already been dealloctated. - alksize = sizeof(s);does not do what you'd expect. It returns the size ofs.sis a pointer, and a pointers size is either 4 or 8 depending on the platform. Usestrlen()instead. - alk