There are several problems.
First, p
should point to the array's first element, so you should have p = &a[0]
.
You can also rely on implicit conversion and just write p = a;
, which is exactly the same.
&a[10]
is the pointer "one-past-the-end" of the array, and dereferencing it is undefined.
Next, you want max
to point to the maximum element.
It should also start at the beginning of the array, like p
.
Then, when you find a new maximum, you should make max
point to that element, not change the value max
points to.
Lastly, index
will always be 10 after the search loop.
(Take a few moments to think about why.)
You don't need it – the index is the difference between the location of the maximum element and the beginning of the array.
int main()
{
int a[10];
for(int i = 0; i < 10; i++)
cin >> a[i];
int* max = &a[0];
int* p = &a[0];
for (int index = 0; index < 10; index++){
if (p[index] > *max){
max = &p[index];
}
}
cout << "Highest value= " << *max << endl << "is at index= "<< max - a << endl;
}
if((p[index])>*max){
on the first iterationmax
is a null pointer. So you can't dereference it.*max=(p[index]);
is also wrong for a similar reason. – drescherjm Jun 2 '20 at 15:02*max
becausemax
is a null pointer. – drescherjm Jun 2 '20 at 15:05