char *, promem and function problem

I'm making a function to return a string from a PROGMEM variable.
I'm getting strange characteres on the LCD, I bellive that's because I'm using char* on my function, how can I solve this?

This code doesn't work, prints strange characteres on the lcd ~~~~~~~~~

char* Message(int which) {
char buffer[30];
strcpy_P(buffer, (char*)pgm_read_word(&(MessagesTXT[which])));
return buffer;
}

lcd.print(Message(0));

This code works ~~~~~~~~~~~~

char buffer[30];
strcpy_P(buffer, (char*)pgm_read_word(&(MessagesTXT[0])));
lcd.print(buffer);

In the function, you have this:

   char buffer[30];
   strcpy_P(buffer, (char*)pgm_read_word(&(MessagesTXT[which])));
   return buffer;

buffer is allocated on the stack. Then, some data is copied into it, and then you return a pointer to that location on the stack. The function returns, and unwinds the stack. Now your pointer points to garbage.

You must pass the function a pointer to a memory location that it can write to.

void Message(int which, char *where)
{
   strcpy_P(where, (char*)pgm_read_word(&(MessagesTXT[which])));
}

Then call it:

char buffer[30];
Message(0, buffer);

Hi Paul,

What is strange (to me) is that the function works if I print to serial Serial.println(Message(0));

What is strange (to me) is that the function works if I print to serial Serial.println(Message(0));

The stack is not destroyed immediately. All that changes is the stack pointer. But, call another function, and at least part of the stack is destroyed. How much depends on how many functions are called, and how many arguments the functions have, and what those argument types, and the return type, are. In any case, it is NOT safe to rely on data on the stack after a function ends.