Returning a C string from a function

Viewed 361335

I am trying to return a C string from a function, but it's not working. Here is my code.

char myFunction()
{
    return "My String";
}

In main I am calling it like this:

int main()
{
  printf("%s", myFunction());
}

I have also tried some other ways for myFunction, but they are not working. For example:

char myFunction()
{
  char array[] = "my string";
  return array;
}

Note: I am not allowed to use pointers!

Little background on this problem:

There is function which is finding out which month it is. For example, if it's 1 then it returns January, etc.

So when it's going to print, it's doing it like this: printf("Month: %s",calculateMonth(month));. Now the problem is how to return that string from the calculateMonth function.

15 Answers
char* myFunction()
{
    return "My String";
}

In C, string literals are arrays with the static constant memory class, so returning a pointer to this array is safe. More details are in Stack Overflow question "Life-time" of a string literal in C

Return string from function

#include <stdio.h>

const char* greet() {
  return "Hello";
}

int main(void) {
  printf("%s", greet());
}

Another thing to keep in mind is that you can’t return a string defined as a local variable from a C function, because the variable will be automatically destroyed (released) when the function finished execution.

#include <stdio.h>
#include <stdlib.h>

char *myfunc(){
    char *myvar = (char *)malloc(20);
    printf("Plese enter some text \n");
    fgets(myvar, 20, stdin);
    return myvar;
}
int main(){
    printf("You entered: %s", myfunc());
}
Related