Help with returning pointer to char.

Hello, my teacher gave me this program to test what wrong with it.

1
2
3
4
5
6
7
8
9
10
11
12
#include <stdio.h>

char * get_message(void) {
	char msg[] = "Apontadores são massa!";
	return msg;
}

int main (void) {
	char *string = get_message();
	puts(string);
	return 0;
}


The output is a empty line. What's the problem?

You are declaring the message in the local scope of another function . Because you are returning a pointer, the program returns a pointer to a memory location, and not the string itself. When the function goes out of scope, the pointer becomes invalid.

Try returning a const char* instead of just a char*
Last edited on
Thanks, but could you post the code with the fix, please? Otherwise, thank you.
@grady
Try returning a const char* instead of just a char*

It is not important whether char * or const char * will be used. The program has undefined behavior.
Last edited on
Topic archived. No new replies allowed.