[help] char [] and char *

I dont understand why my program 1 can't show : Hello World
Can you help me explain?
(I tried on cpp.sh and Repl.it)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <stdio.h>
char* getmessage(void)
{
    char mes[] = "Hello";
    char *ret = &mes[0];
    //printf("%s\n",ret);
    return ret;
}
int main(void)
{
    printf("%s World\n",getmessage());
    return (0);
}

Output : nothing

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <stdio.h>
char* getmessage(void)
{
    char mes[] = "Hello";
    char *ret = &mes[0];
    printf("%s\n",ret);
    return ret;
}
int main(void)
{
    printf("%s World\n",getmessage());
    return (0);
}


Output :
Hello
Hello World
Last edited on
Neither works because the code is wrong.

You're returning a pointer to a local variable, which means the memory you're pointing at in main no longer exists (in the form you expect it to).

Oh sure, the memory is still there, it's just that it doesn't contain "Hello" anymore, because it's being used for something else.

Try it with
static char mes[] = "Hello";
thank @salemc
as your comment, why do my example 2 print : "Hello" and "Hello World"?
you print in the function, line 7, which prints "hello" an then on line 12, which prints "hello world".
as your comment, why do my example 2 print : "Hello" and "Hello World"?
For "Hello World": It is undefined behavior. That it accidentally do what you expect doesn't mean it is correct.
For "Hello": it is actually correct.
he may have added static but didn't update the code here.
> as your comment, why do my example 2 print : "Hello" and "Hello World"?
Because it can.

The code is still broken, but one of the really annoying things about broken code is that despite all your efforts to make a mess of it, it still manages to produce the answer you expect.

Therein lies the trap. Just because you got the answer you expected, that in itself is NOT an argument that your code is bug free.

You make a small change, like calling printf in getmessage, and you mysteriously achieved success.
The problem is, you can make another small change and it can just as easily stop working.


Topic archived. No new replies allowed.