fork download
  1. #include <iostream>
  2.  
  3. // return pointer to location from function
  4. double* maximum(double *a, int size)
  5. {
  6. if (size == 0) return 0;
  7.  
  8. // initialize both variables
  9. double* max_pos = a; // points to the value in a[0]
  10. double maxVal = *max_pos; // this is the starting max value
  11. std::cout << "max_pos = " << max_pos << " (" << maxVal << ")" << std::endl;
  12.  
  13. for(int i = 1; i < size; ++i){
  14. if (a[i] > maxVal){
  15. max_pos = &a[i];
  16. maxVal = *max_pos;
  17. std::cout << "max_pos = " << max_pos << " (" << maxVal << ")" << std::endl;
  18. }
  19. }
  20.  
  21. // return address
  22. return max_pos;
  23. }
  24.  
  25. int main()
  26. {
  27. const int arrSize = 5;
  28. double myarr[arrSize];
  29.  
  30. std::cout << "Input " << arrSize << " floating point values for your array" << std::endl;
  31.  
  32. for(int i = 0; i < arrSize; ++i){ // loop to input values
  33. std::cin >> myarr[i];
  34. }
  35.  
  36. for(int j = 0; j < arrSize; ++j){
  37. std::cout << "Location for " << myarr[j] << " = " << &myarr[j] << std::endl;
  38. }
  39.  
  40. double* maxNum = maximum(myarr, arrSize);
  41. std::cout << "maxNum = " << maxNum << " (" << *maxNum << ")" << std::endl;
  42.  
  43. return 0;
  44. }
Success #stdin #stdout 0s 4484KB
stdin
1
2
3
4
5
stdout
Input 5 floating point values for your array
Location for 1 = 0x7ffd36011830
Location for 2 = 0x7ffd36011838
Location for 3 = 0x7ffd36011840
Location for 4 = 0x7ffd36011848
Location for 5 = 0x7ffd36011850
max_pos = 0x7ffd36011830 (1)
max_pos = 0x7ffd36011838 (2)
max_pos = 0x7ffd36011840 (3)
max_pos = 0x7ffd36011848 (4)
max_pos = 0x7ffd36011850 (5)
0x7ffd36011850 (5)