C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Pointers in C

Function returning pointer to string with dynamic allocation

C Program: Function Returning Pointer to String

C

#include <stdio.h>

 

// Function that returns a pointer to a string

char* greetMessage() {

    return "Welcome to C Programming!";

}

 

int main() {

    char *message;

 

    // Function call

    message = greetMessage();

 

    // Display returned string

    printf("%s\n", message);

 

    return 0;

}

Output

 
OUTPUT :
Welcome to C Programming!

Explanation

  • The function greetMessage() returns a pointer to a string literal.
  • String literals are stored in static memory, so their addresses remain valid after the function returns.
  • The pointer message in main() receives the address returned by the function.
  • The program then prints the string.