Skip to content

How to return a string from a C function

New Course Coming Soon:

Get Really Good at Git

Learn how to return a string from a C function

In one of my C programs, I had the task to return a string from a function:

xxxxx myName() {
  return "Flavio";
}

The tricky thing is defining the return value type.

Strings in C are arrays of char elements, so we can’t really return a string - we must return a pointer to the first element of the string.

This is why we need to use const char*:

const char* myName() {
  return "Flavio";
}

Here’s an example working program:

#include <stdio.h>

const char* myName() {
  return "Flavio";
}

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

If you prefer to assign the result to a variable, you can invoke the function like this:

const char* name = myName();

We can write the pointer operator * also in this ways:

const char * myName()
const char *myName()

All forms are perfectly valid.

Note the use of const, because from the function I’m returning a string literal, a string defined in double quotes, which is a constant.

Note that you can’t modify a string literal in C.

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, and as such it will not be available, if you for example try do do:

#include <stdio.h>

const char* myName() {
  char name[6] = "Flavio";
  return name;
}

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

you’ll have a warning, and some jibberish, like this:

hello.c:5:10: warning: address of stack memory
      associated with local variable 'name'
      returned [-Wreturn-stack-address]
  return name;
         ^~~~
1 warning generated.
B��Z> K���⏎

Notice the B��Z> K���⏎ line at the end, which indicates that the memory that was first taken by the string now has been cleared and there’s other random data in that memory. So we don’t get the original string back.

Changing myName() to

const char* myName() {
  char *name = "Flavio";
  return name;
}

makes the program work fine.

The reason is that variables are allocated on the stack, by default. But declaring a pointer, the value the pointers points to is allocated on the heap, and the heap is not cleared when the function ends.

Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching May 21, 2024. Join the waiting list!
→ Get my C Handbook

Here is how can I help you: