2

From my main method, I want to declare an array of doubles (but not initialize it) and pass that to a function. In that function, the array will be initialized with some values. Now back in my main method, I want to read and display those values.

populateValues (double*& values) {

    values [0] = 100;
    values [1] = 200;
    values [2] = 300;

}


int main() {

    double values[3];
    populateValues(values);

    for (int i=0; i <3; i++) {
        std::cout << values[i] << std::endl; 
    }

}

However, when I compile the above, I get the error message:

error: invalid initialization of non-const reference of type ‘double*&’ from an rvalue of type ‘double*’

There is something wrong in how I am passing the parameter no doubt, but I don't know how to fix it.

didjek
  • 393
  • 5
  • 16
  • 1
    `populateValues (double* values)` – SergeyA Nov 08 '18 at 16:39
  • 4
    Try avoiding C style arrays. `std::array` and magically the problem is no more. – n. m. could be an AI Nov 08 '18 at 16:53
  • 1
    C++ errors can be a little opaque (mostly because so many things can be valid, that syntax error could be similar to all sorts of valid things.) You can pass the parameter by pointer (*), or reference (&) - but you can't use both at once, like this. You can use an STL array, as @n.m. notes - in which case I would suggest passing by reference (if you use neither, you'll get a local copy, and the values won't be passed back.) – Rags Nov 08 '18 at 16:54

2 Answers2

1
#include <iostream>
void populateValues (double * values) {
    values [0] = 100;
    values [1] = 200;
    values [2] = 300;
}

int main() {
    double values[3];
    populateValues(values);
    for (int i=0; i <3; i++) {
        std::cout << values[i] << std::endl;
    }
}
0

with double values[3];, values is of type double[3] which might decay to double*.

expecting double*& require a true lvalue of type double*. And temporary cannot be bound to no-const reference

You might change to

  • void populateValues(double (&values)[3])
  • void populateValues(double* values)
  • void populateValues(double*const &values) temporary can be bound to const ref.
Jarod42
  • 203,559
  • 14
  • 181
  • 302