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.

3
  • 1
    populateValues (double* values) Commented Nov 8, 2018 at 16:39
  • 4
    Try avoiding C style arrays. std::array<double, 3> and magically the problem is no more. Commented Nov 8, 2018 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.) Commented Nov 8, 2018 at 16:54

2 Answers 2

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;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.