importance of a pointer as an output of a function

Hi friends,

I understand the concept of pointers as input or output of a function. Now I need a good example to show the importance of a pointer as an output of a function or better to say when it is necessary to define a pointer as output of a function.
Ever heard of malloc or new? Those are functions that return a pointer. You can't do dynamic memory allocation without using a function that returns a pointer.
A function has only one return value. If you want to return more things you can add an extra pointer parameter to the function that the function can use as an extra return value.

Example:
Say that you have a function maxMin that should return the maximum and minimum of two values. One way to do this is to let the return value of the function be the maximum value and use an extra parameter to return the minimum value.
1
2
3
4
5
6
7
8
9
10
11
12
13
int maxMin(int value1, int value2, int* outMin)
{
	if (value1 < value2)
	{
		*outMin = value1;
		return value2;
	}
	else
	{
		*outMin = value2;
		return value1;
	}
}

So if you want to find the max and min of two variables, a and b, you could do
1
2
int min;
int max = maxMin(a, b, &min);


In C++ we often prefer to use references instead of pointers wherever possible so if we rewrite the function using references it would look like
1
2
3
4
5
6
7
8
9
10
11
12
13
int maxMin(int value1, int value2, int& outMin)
{
	if (value1 < value2)
	{
		outMin = value1;
		return value2;
	}
	else
	{
		outMin = value2;
		return value1;
	}
}

and to get the max and min of a and b
1
2
int min;
int max = maxMin(a, b, min);
Topic archived. No new replies allowed.