0

So an int* function must retur a pointer to an int, but if a pointer to an int is assigned an int address, could an int* function return an int address? If not, why is it wrong? Thanks

int * function(){

    int a = 4;

    return &a;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Elrisas
  • 49
  • 5

1 Answers1

1

Within the function

int * function(){

int a = 4;

return &a;
}

the variable a is a local variable of the function with automatic storage duration that will not be alive after exiting the function. So the returned pointer will have an invalid value and you may not dereference such a pointer. Otherwise the program will have undefined behavior.

You could declare the variable as having static storage duration like

int * function(){
    static int a = 4;

    return &a;
}

In this case the variable will be alive after exiting the function. So the returned pointer will have a valid value.

Another approach is to allocate an object dynamically and return a pointer to the allocated object as for example

int * function(){
    int *p = malloc( sizeof( *p ) );

    if ( p != NULL ) *p = 4;

    return p;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • Thanks, so "int * function(){ static int a = 4; return &a; }" would be valid? – Elrisas Jun 24 '22 at 20:30
  • @Elrisas Yes, it is a valid code and you may dereference the returned pointer to access the variable a. – Vlad from Moscow Jun 24 '22 at 20:34
  • Okay so basically the int* function can return a pointer to int or an adress of an int if it will be perduring after the function, right? – Elrisas Jun 24 '22 at 20:40
  • @Elrisas I have not understood what you said. The function should return a valid pointer that a pointer that points to an object that will be alive after exiting the function. – Vlad from Moscow Jun 24 '22 at 20:50