1

I have a cpp program which takes some double values as input and calculate the total of the values. Length of the array is not stable. It changes with the number of input. So I chose to use for each loop inside the function.Following is my code.

double getTotal (double arr[]){
   double total = 0;
   for (double x : arr){
      total += x; 
   }
   return total;
}

The above code gives me the following error

main.cpp: In member function ‘double My1DArray::getTotal(double*)’:
main.cpp:39:28: error: ‘begin’ was not declared in this scope
        for (double x : arr){
                        ^

I tried to use arr.size() which gave me a bunch of errors.

What cause the problem?

Ramesh
  • 2,297
  • 2
  • 20
  • 42
  • You can't, because `double arr[]` decays to merely a pointer and doesn't hold that information. Use `std::vector` instead. – Blaze Feb 11 '19 at 11:13
  • It's not really an exact duplicate, but it explains your pointer decay problem well enough. – Useless Feb 11 '19 at 11:14
  • @Blaze You mean `vector &arr` something like this? – Ramesh Feb 11 '19 at 11:17
  • 1
    @Ramesh That's right. Make the vector like `std::vector arr;`, and for the function signature, put `double getTotal (vector &arr)`. – Blaze Feb 11 '19 at 11:18
  • @Useless I checked the question before. But the pointer stuffs are really new to me and made me little confused. Can you give me little explanation regarding this. – Ramesh Feb 11 '19 at 11:18
  • 1
    @Blaze it saved my time sir. Thank you – Ramesh Feb 11 '19 at 11:20
  • 1
    You may also want to take a look at [std::accumulate](https://en.cppreference.com/w/cpp/algorithm/accumulate) – Ted Lyngmo Feb 11 '19 at 11:22

0 Answers0