Pointer question...

This is a ridiculously simple function that I just can not seem to get to work. I am getting a segmentation fault error for this every time I run it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 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 *p1;
	int *largestIndex;
	
	for(p1 = &array[0]; p1 < &array[n]; p1++)
	{
			if(*p1 > array[n])
			{
				*largestIndex = *p1;
			}
	}

return largestIndex;
}


I did some debugging and the program will run all the way through until it hits -> *largestIndex = *p1; which is where I am given the error. Any advice?
*largestIndex = *p1;

Here, largestIndex is uninitialized (it's not pointing to anything), so you're dereferencing an uninitialized pointer.

Why don't you just return the largest integer?
Initializing it has no affect on the outcome. I am still receiving the segmentation error. Also, the program that this is being used wants a pointer to the largest element, thus the function must return a pointer to the largest element.

:(
Initializing it has no affect on the outcome.

Just doing int *largestIndex = 0; won't help either. It has to point to something, i.e.

const int *largestInteger = &array[0];

That would cause the segmentation fault to go away. Notice how I put const in front.

You will also have to do the following because you won't be able to change what largestInteger points to:

1
2
3
4
if(*p1 > array[n])
{
    largestIndex = p1;
}

There's also a problem with this statement if(*p1 > array[n]). You won't be getting the largest element in this case, but rather the element closest to the end that's larger than array[n].
Last edited on
Topic archived. No new replies allowed.