C – Function returning pointer

A function returning address: A function can return address of aggregate data type variable or user defined data type variable to access the data.

int* add(int,int);
void main()
            int a, b, *c;
            printf(“enter two numbers : “);
            c = add(a,b);
            printf(“sum : %d\n”,*c);
int* add(int x, int y)
            int z;
            return &z;

Dangling pointer:

  • In the above code, add function returns the address of local variable.
  • Local variables will be deleted once the function execution completes.
  • As we return the address of location, the value of that location may change by another function before processing the data.
  • Hence Dangling pointers will not provide accurate results(values).
int *fun()
            int x = 5;
            return &x;
int main()
            int *p = fun();
            printf(“%d”, *p);
            return 0;
Scroll to Top