Functions that return a pointer

  • Thread starter Thread starter woofr_87
  • Start date Start date
  • Tags Tags
    Functions
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
3 replies · 2K views
woofr_87
Messages
4
Reaction score
0
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.. I am 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));






}
 
Physics news on Phys.org
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:
    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:
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:
@Mark44...Thanks for your respond...but I am still unclear...can you explain more detail about this...
Mark44 said:
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).
 
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 *.