Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array inside a structure

Tags:

c++

arrays

struct

I want to create a structure that holds arrays with fixed size inside:

struct smt{
   int array1[3];
   int array2[10];
   int bananas;
};

So that I can use it in my main code. However, when I try to fill the arrays I always get an error:

int main(){
   smt name;
   name.array1 = {1,2,3};

   return 0;
}

The errors are on the name.array1 = {...}; line:

error C2059: syntax error : '{'
error C2143: syntax error : missing ';' before '{'
error C2143: syntax error : missing ';' before '}'

Any help would be appreciated. I've tried to find similar problems but haven't found anything helpful so far.

like image 660
Daniel Jaló Avatar asked Dec 26 '22 13:12

Daniel Jaló


1 Answers

You can't do it like this if it's not in the initialization. You should do:

name.array1[0] = 1;
name.array1[1] = 2;
name.array1[2] = 3;

See this helpful answer:

It's not just arrays, you cannot provide an initializer for anything at any point other than in a definition. People sometimes refer to the second statement of something like int i; i = 0; as "initializing i". In fact it's assigning to i, which previously holds an indeterminate value because it wasn't initialized. It's very rarely confusing to call this "initializing", but as far as the language is concerned there's no initializer there.

like image 88
Maroun Avatar answered Dec 28 '22 07:12

Maroun