So far we have studied functions that either return a value or have a void return type. A function can also return a pointer to a data item of any type. However, we must be careful while returning pointers from a function. A common mistake would be to return a pointer to a local variable or value parameter in that function as they are destroyed when control returns to the calling function.
In situations where we have to return a pointer to a local variable, we must allocate the memory for such variables using dynamic memory management techniques, i.e., using malloc, calloc and realloc standard· library functions. Such dynamically allocated variables last till the end of program execution. Thus, the memory allocated using these functions is not destroyed when the control returns to the calling functions.
Example of Returning a Pointer from a Function
Consider that we wish to write a function that accepts two integer numbers and returns a pointer to the smaller number. The function bad_pmin1 given below has two value parameters (a and b) and return type of pointer to int. Within this function, the smaller number is first determined in variable small whose address is then returned as expected. However, this implementation is incorrect as it returns the address of a local variable. ·
int *bad_pminl(int a, int b) /* INCORRECT FUNCTION */
{
int small = (a < b) ? a : b;
return &small; /* Wrong: can’t return addr of local variable */
}
The function bad_pmin2 given below is also incorrect as it returns the address of one of the function parameters which, as we know, is local to the function.
int main()
{
short int a = 6;
float x = 1.23;
printf(“short int : %4hd Binary: “, a);
print_binary((unsigned char*) &a, sizeof(a));
printf(“\nfloat : %0.2f Binary: “, x);
print_binary((unsigned char*)_ &x, sizeof(x));
return 0;
}
Observe how the address of the variable to be printed is typecast to unsigned char *. The program output is given below.
short int : 6 Binary: 00000000 00000110
float : 1.23 Binary: 00111111 10011101 01110000 10100100