简体   繁体   中英

How do I find highest value using pointer?

I want to find the highest value from an array using two given pointer int *p,*max;, but the code doesn't work.

#include <iostream>
#include <string>
using namespace std;
int main() {
  int a[10], i, index;
  int *p, *max;
  for (i = 0; i < 10; i++) cin >> a[i];
  max = 0;
  p = &a[10];
  for (index = 0; index < 10; index++) {
    if ((p[index]) > *max) {
      *max = (p[index]);
    }
  }
  cout << "Highest value=" << *max << endl << "is at index=" << index << endl;
  return 0;
}

The code is buggy. First of all, you assign

p=&a[10];

This assigns p to a memory address past a . Furthermore, you then index as p[index] , which essentially is the same as a[10 + index] .

Also, max is a wild pointer. It does not point to anything. You are assigning values to an undefined memory location.

I would strongly suggest to read up on pointers and to properly understand them before using them. Also, in modern C++, it is not very often than you need pointers.

Also, in idiomatic C++, we would probably write

auto p = std::max_element(a, a + 10);

The solution to this problem is recognizing that max should always point to the maximum item seen in the array a so far so instead of initializing max to 0 you start by initializing it to point to the first item in a which is &a[0] or just a.

I tried to make the least amount of changes to the original code:

#include <iostream>
#include<string>
using namespace std;
int main()
{
    int a[10],i,index;
    int *p,*max;
    for(i=0;i<10;i++)
        cin>>a[i];
    max=a; // Initialize max to point to the first item in a
    p=a;
    for(index=0;index<10;index++){
        if((p[index])>*max){
            max=(&p[index]); // Now make max point to the new maximum item
        }
    }
    cout<<"Highest value="<<*max<<endl<<"is at index="<<max - p<<endl;
    return 0;
}

Here is the code in ideone: https://ideone.com/BwE45C

As mentioned in the comments below p probably is not being used as the question expects so I have rewritten the code to iterate using p

#include <iostream>
#include<string>
using namespace std;
int main()
{
    int a[10],i,index;
    int *max;
    for(i=0;i<10;i++)
        cin>>a[i];
    max=a;

    for(int* p=a;p<a+10;p++){ // p is now a pointer that is used to iterate through the array
        if(*p>*max){
            max=p; // max points to the new maximum 
        }
    }
    cout<<"Highest value="<<*max<<endl<<"is at index="<<max - a<<endl;
    return 0;
}

The new ideone link for this is here: https://ideone.com/bk3zoS

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;
}

I'd remove p and use a range-based for-loop where possible and iterators when it'll improve performance.

Comments in the code:

#include <iostream>
#include <iterator>

// using namespace std; // don't do this

int main() {
    using std::cin, std::cout;

    int a[10];

    // use a range-based for-loop:
    for(int& aref : a) { // aref is a reference to the current element in a

        // check that extraction from std::cin actually works
        if(!(cin >> aref)) {
            std::cerr << "error reading int\n";
            return 1;
        }
    }

    // initialize max to point at the first element
    auto max = std::begin(a);

    // Start at the second element since max is already set to point at the first element.
    // Don't use magic numbers. Define a constant or use std::size(<array>)
    // ...or use iterators like in this example:
    for(auto curr = std::next(std::begin(a)); curr != std::end(a); ++curr) {
        if(*curr > *max) {
            max = curr;
        }
    }

    // you can use std::distance ot calculate the index for max:
    cout << "Highest value=" << *max << '\n'
         << "is at index=" << std::distance(std::begin(a), max) << '\n';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM