0

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.

// 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. Also, *p1 holds the correct value at that point. So, I am lost! :) Any advice?

2
Contributors
1
Reply
2
Views
6 Years
Discussion Span
Last Post by mike_2000_17
0

Here are a few comments:

int *LargestUsingPointers(const int *array, int n)
{
  const int *p1;
  int *largestIndex; //you create a pointer that points nowhere, because it is uninitialized.
	
  for(p1 = &array[0]; p1 < &array[n]; p1++)
  {
    if(*p1 > array[n])  //you check if the current element is greater than an element that is passed the end of the array and thus, does not exist.
    {
      *largestIndex = *p1;  //you write the value of the current element to a location in memory that is arbitrary and not allocated for this program (and thus, the 'segmentation fault').
    }
  }

  return largestIndex;  //you return a pointer to nowhere.
}

A segmentation fault means that you are attempting to read/write memory that is not assigned to your program, which is what will happen if you dereference a pointer that is not initialized to actually point somewhere.

I think that the intent of your function is to return a pointer that points to the element of the array that is the largest. In which case, this makes more sense:

const int *LargestUsingPointers(const int *array, int n)
{
  const int* largestIndex = &array[0]; //initialize the largestIndex pointer to point to the first element.
  
  for(const int* p1 = &array[1]; p1 < &array[n]; p1++) //iterate through the other elements.
  {
    if(*p1 > *largestIndex) //compare with the current "largest" element.
    {
      largestIndex = p1; //reset the current "largest" element pointer.
    }
  }

  return largestIndex; //return the largest element pointer.
}

Edited by mike_2000_17: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.