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(constint *array, int n)
{
constint *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?
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.
Just doing int *largestIndex = 0; won't help either. It has to point to something, i.e.
constint *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].