Returning a Pointer from a Function in C

We have already seen a function can return data of types int , float, char etc. Similarly, a function can return a pointer to data. The syntax of a function returning a pointer is as follows.

Syntax: type *function_name(type1, type2, ...);

Some examples:

The following program demonstrates how to return a pointer from a function.

Expected Output:

How it works:

Since the name of an array is a pointer to the 0th element of the array. Here we are passing two arguments to the function return_pointer(). The arr is passed using call by reference (notice that name of the array is not preceded by & operator because the name of the array is a constant pointer to the 0th element of the 1-D array) and i is passed using call by value. Inside the function pointer p is incremented by n and reassigned to p. Finally, the pointer p is returned to the main() function and reassigned to ptr.

Never return a pointer to local variable from a function.

Consider the following code.

Can you point out the problem with above code?

In the function abc() we are returning a pointer to the local variable. Recall that a local variable exists only inside the function and as soon as function ends the variable x cease to exists, so the pointer to it is only valid inside the function abc().

Even though the address returned by the abc() is assigned to ptr inside main(), the variable to which ptr points is no longer available. On dereference the ptr you will get some garbage value.

Note: Sometimes you may even get the correct answer i.e 100, but you must never rely on this behaviour.

4 thoughts on “Returning a Pointer from a Function in C

  1. You can use static variable inside the function to return its pointer to the caling function. Static variable inside function have a local scope but dont get erased from memory(they are not stored in the stack unlike local variables) once the function returns.

  2. how to return whole array not only the last element of the array
    i am returning char array similarly but, since last element of char is null
    so it is only returning null.
    please tell me how i can return whole array?

    • Just return the pointer to the array.

Leave a Comment

%d bloggers like this: