Question: I am learning C and I want to implement a function that returns to main function a string. I have read some topics here but I got confused.. I wrote:

```
#include <stdio.h>
#include <string.h>

char myPrint(int); 

int main()
{ 
   char msg[10];

   msg = myPrint(1);

   printf("\n %s \n", msg); 
} 

char myPrint(int n)
{ 
   char msg[10];

   if(n==1)
      strcpy(msg, "ACCEPT");
   else
      strcpy(msg, "DENY");

   return msg;
}

```

and I get a bunch of warnings and error.. I read [this](http://www.tutorialspoint.com/c_standard_library/c_function_strcpy.htm) for the usage of the strcpy 
and many others links relevant to this topic but I didn’t get it..

Answer: 
Declare your function as 

```
char *myPrint(int n);

```

Do not return the local variable `msg` from your function - it ceases to exist after `myPrint` function.

```
 if(n==1)
     return "ACCEPT";
 else
     return  "DENY";

```
You should never return a pointer to variable that is allocated in the function, because by the time it returns, the variable will be de-allocated automatically (it is stack-allocated as opposed to heap-allocated or static). So instead, you pass in a char \* to myPrint and fill the char array from inside it. Then the outer function that declared the char array can access it without error. Note though that the following is still not best practice, because it allows for buffer overruns when one passes in a pointer to an array that is shorter than length of "ACCEPT" + 1 (+1 for terminating \0 character).

```
void myPrint(char *msg, int n)
{
    if (n == 1)
    {
        strcpy(msg, "ACCEPT");
    }
    else
    {
        strcpy(msg, "DENY");
    }
}

int main()
{
    char msg[10];
    myPrint(msg, 1);
    printf("\n %s \n", msg); 
}

```