# Functions that return a pointer

1. Feb 3, 2010

### woofr_87

hye everyone...

i want to build a program where the program with a function that returns a pointer to the maximum value of an array of double. if the array is empty, the program should return NULL.

here is my code, but still have an error... every week i try to solve this problem but....hmmm.. im new in programming...

can anyone assist me to solve my problem...

PHP:
#include <stdio.h>

double* maximum(double* a, int size);

double* maximum(double* a, int size)
{
double max = 0;

int i;

if(a==NULL || a[i]==NULL)
{
printf("NULL");
}

else
{

for(i=0;i<size;i++)
{

if(a[i]>max)
{
max=a[i];

//ptr_max = &max;
//result2 = *ptr_max;

//result2 = max;

return max;
}
}
}

}

void main()
{
double array[4]={30.00,20.00,70.00,10.00};
//maximum(array,4);
//  double result;

//result = maximum(array,4);
printf("The largest number is : %0.2f",maximum(array,4));

}

1. The problem statement, all variables and given/known data

2. Relevant equations

3. The attempt at a solution

2. Feb 3, 2010

### Staff: Mentor

Your function is actually returning a double, not a pointer to a double (double*). Here are a couple of lines in your maximum function.
Code (Text):

double max = 0;
.
.
// Calculate the maximum value of the passed array.
.
return max;

The quickest fix is to change your function prototype and definition so that it returns a double, like so:
Code (Text):

double maximum(double* a, int size);
double maximum(double* a, int size)
{
.
.
.
}

BTW, since your maximum function is defined above main(), you don't need the prototype. The compiler treats your function definition as also a declaration. If you had the definition of maximum below main(), then you would need the prototype.

If for some reason you really want to return a pointer to a double, then you won't be able to have a variable that is local to maximum as the thing you return, at least if that variable's storage class is automatic (allocated on the stack). The reason for this is that variables that are local to maximum spring to life when the function is entered, and die off when the function exits. Having a pointer to a variable that no longer exists does you no good.

Last edited: Feb 3, 2010
3. Feb 3, 2010

4. Feb 3, 2010

### Staff: Mentor

Read in your text or reference book about storage class specifiers - auto, static, extern. To fix your problem, just have the function return a double, not a double *.