简体   繁体   中英

C++ Returning Pointers

I am trying to write a program that will: The function returns a pointer to the maximum value of an array of double values. If size is 0, then return the special pointer value NULL (or 0).

I am not sure if my logic is correct or if the function is returning a address or the value of temp.

const double * pMax(const double a[], size_t size){

    double * ptr;

    for(size_t i = 0; i < size; i++){
        if(a[i] > a[i+1]){
            ptr = a[i];
           }
       }      
    return ptr;
}

error: cannot convert 'const double' to 'double*' in assignment ptr = a[i];

Get rid of your temp variable: you should never return a pointer to a local variable within a function, because by the time the caller receives the returned pointer, the variable it points to has gone out of scope. Instead, you should return a pointer to one of the elements in the the a array.

An overview of the algorithm to use:

  • Initialize ptr to NULL . This is the default value, until it's changed by checking at least one number in the array.
  • Iterate through the array with a loop. (If the array is empty, ie size is 0, the loop will run zero times.)
  • Each time through the loop, if ptr is NULL or the value that it points to (ie *ptr ) is less than the current array element, change ptr to point to the current array element. This'll make it point to the first value initially, and then modify it to point to a different element whenever a greater one is found.
  • When the loop finishes, ptr points to the greatest element in the array that was found by the loop. If the loop didn't run any iterations (because size is 0), ptr is still NULL . Either way, this is the result you want, so return it.

You need to initialize ptr to NULL to take care of the case when array contains no element. For all other cases, it iterates through the array, to find out pointer to the max element and returns that. Also, In the program snippet, if the last element in the array is the largest, it does not compute pointer to that. Because, when the loop ends at i == (size-1), a[i+1] will cause array index to go out of bounds, risky. Here's the corrected version:

const double * pMax(const double a[], size_t size){
 const double * ptr = (size == 0) ? NULL : &a[0];
 for(size_t i = 1; i < size -1; i++){
  if (a[i] > *ptr){
    ptr = &a[i];
  }
 }      
 return ptr;
}

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