I am studying C programming and making some tests in Ubuntu with Geany. I have a question about pointers. When an array is declared in a function and then returned as a pointer, array values are lost in the main method. I could check this with a simple example:
#include <stdio.h>
char* msg ();
int main(int argc, char **argv)
{
char* p = msg();
int i;
for(i=0;i<=10;i++)
printf("i: %d, value: %c \n", i, p[i]);
return 0;
}
char* msg (){
char msg [] = "hello";
return msg;
}
The output is random values (excepting the first one that always is 'h'). I suppose that this is because the pointer passed out of the scope and the memory could be written by other functions.
But if the value of message is bigger enough (like thousands of characters for example or maybe less), values stand in the same memory place and I can read them despite of the array was created in other function.
What is the reason for this results?
Thank you so much.