Another Pointer Question...

Ok, so I am still trying to get a grasp on the pointers and references...here is my latest quandary:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// LargestUsingPointers:  receives an n-element integer array and returns
// a pointer to the largest element; the function uses pointers
int *LargestUsingPointers(const int *array, int n)
{
	const int *p;
	int num = 0;
	int *index;
	int count = 0;

	for (p = &array[0]; p < &array[n]; p++)
	{
		
		if (*p > num)
		{
			num = *p;
			index = &array[count];
		}	
	count++;
	}
	return index;
}


Everything works correctly except the index = &array[count] line.

I get that cannot convert const int* to int* error...that error is starting to be the bane of my existence...haha.

Thanks for any help.
The error is just as it says. You can't convert a const int* (array) to an int* (index).

The reason for this is because it would allow you to side-step the const-ness:

1
2
3
4
5
6
7
// an example of why you can't do this:
const int example = 5;  // a contant value of 5

int* ptr = &example;  // converting a const int* to an int*
    //  fortunately, this is illegal and the compiler will give you an error

*ptr = 0;  // here we are changing 'example', even though it is const!!! 



To solve this in your situation, you have a few options:

1) Change 'index' and the function return type to be const int* instead of int*

2) Change 'array' to be an int* instead of a const int*

3) (mentioned only for completeness -- I don't recommend this approach at all), cast away the constness with const_cast (but again -- bad idea)
I wish I could just change the types and do it that way, but the actual function types have to stay the same. I guess what is really throwing me is that the return type has to be an int pointer, but the array that I need to index is a const int pointer. I can't seem to figure out the right way to get the index into an int pointer and return it as an int pointer, too.

I was never a big fan of pointers or references, which is probably why I never took the time to learn them very well.
I was never a big fan of pointers or references, which is probably why I never took the time to learn them very well.


You're crippling yourself; it's really, really worth learning, and it's really, really not difficult.
Not learning how to use pointers and references is like trying to play World of Warcraft with only a two button mouse, no scroll wheel.

Sure it's possible, but everything is harder than it should be, it all takes way too long, takes way too much brain power, and eventually you're going to find out that there are things that just aren't possible.

That's beside the point that just about every part of polymorphism deals with pointers, and if you're not learning to be polymorphic, you're basically destroying any advantage that C++ has over say...assembler.
Topic archived. No new replies allowed.