Error on "Set" function for Struct (cannot convert ‘<brace-enclosed init>)

I apologize, as this is a pretty basic "set" function and shouldn't be so hard, but I don't understand the error. There is more code to the program, but I think what I put out there is adequate to address the problem. The error is referring to the array being passed into the function on line 28 of the code below.

error: cannot convert ‘<brace-enclosed initializer list>’ to ‘double*’ for argument ‘4’ to ‘void set(ABC&, unsigned int, char, double*)’|

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30

#include <iostream>
#include <cstdlib>

using namespace std;

struct ABC{

    unsigned n;
    char c;
    double a[3];
};


void set( ABC & x, unsigned n, char c, const double a[3] ){

    x.n = n;
    x.c = c;

    for (unsigned i = 0; i < 3; i++){
    x.a[i] = a[i];
    }
}

int main(){

    ABC xx = {number, m, {1, 2, 3}};
    set(xx, 1234, '?', {10.0, 20.0, 30.0});

}
Last edited on
This is because, even though you have specified that you are passing an array of doubles in your set function, it is actually a pointer. Instead, you need to cast the initializer list properly, like so:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
struct ABC {
    unsigned n;
    char c;
    double a[3];
};

void set(ABC& x, unsigned n, char c, const double* const a) {
    x.n = n;
    x.c  = c;
    for (std::size_t i = 0; i < 3; ++i)
        x.a[i] = a[i];
}

int main() {
    ABC xx = {5, 'm', {1, 2, 3}};
    set (xx, 1234, '?', (const double[]){10.0, 20.0, 30.0});
}


Alternately, you can set the function to take an initializer list as an argument, or use std::array instead.
Topic archived. No new replies allowed.