Comparing Pointer in an If Statement

Hello,

I am working on my Unix programming assignments and have run into a block. I am trying to be able to compare two pointers, then return the value of the largest one. Here is what I have so far, but it isn't working...

Edited to add: I get g++ compiler errors stating:

error: cannot convert `const int**' to `const int*' in assignment
error: invalid conversion from `const int*' to `int'

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// Function Larger has two parameters, each a pointer to a const int.
// The function returns the larger of the two int values.
int Larger(const int *a, const int *b)
{	
	const int *p, *q;
	p = &a;
	q = &b;

	if (p > q)
	{
		return p;
	}else{
		return q;
	}
}
Last edited on
I am trying to be able to compare two pointers

Really? I think, based on the phrase "The function returns the larger of the two int values" that you're actually trying to compare two int values, and you have a pointer to each int. Comparing pointers is not the same as comparing what those pointers are pointing to.

Try this:

1
2
3
4
5
6
7
8
9
10
11
// Function Larger has two parameters, each a pointer to a const int.
// The function returns the larger of the two int values.
int Larger(const int *a, const int *b)
{	
	if ((*a) > (*b) )
	{
		return (*a);
	}else{
		return (*b);
	}
}


or, if you insist on extra variables

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// Function Larger has two parameters, each a pointer to a const int.
// The function returns the larger of the two int values.
int Larger(const int *a, const int *b)
{	
	int p, q;
	p = *a;
	q = *b;

	if (p > q)
	{
		return p;
	}else{
		return q;
	}
}


although I like this:

1
2
3
4
5
6
// Function Larger has two parameters, each a pointer to a const int.
// The function returns the larger of the two int values.
int moremoreLarger(const int *a, const int *b)
{
  return(*a > *b ? *a : *b);
}
Last edited on
And I like this: return std::max(*a,*b);
Thanks for the replies...I ended up writing something similar to

1
2
3
4
5
6
7
8
9
10
11
// Function Larger has two parameters, each a pointer to a const int.
// The function returns the larger of the two int values.
int Larger(const int *a, const int *b)
{	
	if ((*a) > (*b) )
	{
		return (*a);
	}else{
		return (*b);
	}
}


I am going to have to keep return std::max(*a,*b); in mind for the future, though. :)
Topic archived. No new replies allowed.