简体   繁体   中英

Too many initializer values while passing boolean array as function input

Good day everyone. I'm working on this Game of Life problem and trying to pass an array of boolean:(Given)

game({0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0}, 15, 9);

into the function below:(Given)

void game(bool cells[], int size, int num_gen) 

However, I'm getting this error: Too many initializer values C/C++ (146)

I tried to play around and was able to pass in values by declaring the array in the main function:

int main(void) 
{
    int cells[]={0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0};
}

But this is my school assignment, so I'm not supposed to edit any given codes/inputs/functions.

I'm kinda lost now, will appreciate any inputs. Thanks in advance!

void game(bool cells[], int size, int num_gen)

The first parameter of your function is not an array. Sure, you declared the parameter to be an array of unspecified length, but such parameter will be adjusted to be a pointer to element of such array. A function parameter is never an array in C++.

As such, you are attempting to initialise a pointer with a brace-enclosed list of values. There are more than one value, so it's wrong (and the types of the values are also incompatible with a pointer).

You can create an array, and pass a pointer to element of that array:

int cells[]={0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0};
game(cells, std::size(cells), 9);

You can use compound literal for this.

Something like

game((bool []){0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0}, 15, 9);

A list of values in braces is not valid at an expression. What you need is a compound literal :

game((bool []){0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0}, 15, 9);

The syntax that looks like a cast before the braced segment gives you the type. You can also use this syntax for a struct literal.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM