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: 
A bit of advice: returning a pointer to a string when that string is defined as a local variable in the function won't work, as the allocated memory for the string will be unvalidated.

If your function returns literal strings, as per your example, you have to do as **Acme** said:

```
char *MyPrint (int n)
{
  if (n==1)
    return "ACCEPT";
  else
    return "DENY";
}

```

As you are returning a pointer to char, you cannot assign that pointer to an array, as you try to do in `main()`. You have to assign it to a variable that must be a pointer to char as well:

```
int main()
{ 
   char *msg;

   msg = myPrint(1);    
   printf("\n %s \n", msg); 
   return 0;
} 

```

If you need to copy the resulting string to an array, then you must use `strcpy()` (or better yer, `strncpy()` ) as this:

```
int main()
{ 
   char msg[10];

   strcpy (msg, myPrint(1) ); /* providing that your function won't ever return a string longer than 9 chars, or bad things will happen */
   printf("\n %s \n", msg); 
   return 0;
} 

```
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); 
}

```