0

Hi I want to ask why do greet function fail to return the pointer

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

char *greet(){

char a[] = "hello world!"
  return a;
}

int main(){


    printf("%s",greet());
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
user13626458
  • 3
  • 1
  • 3

1 Answers1

1

The function returns a pointer to the first element of the local array a that has automatic storage duration.

After exiting the function the pointer becomes invalid because the array is not alive any more.

Either define the function like making the array with the static storage duration

char *greet( void ){

    static char a[] = "hello world!"
    return a;
}

Or use a pointer to string literal that in turn has static storage duration like

char *greet( void ){

    char *a = "hello world!"
    return a;
}

Pay attention to that the parameter list of the function shall contain void.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335