I've been trying to figure out how to add an array into a struct... a struct of ints for example would look like this:
struct test{
int a;
int b;
int c;
} test = {0,1,2};
but if I want to have an array for example:
struct test{
int a;
int b;
int c;
int deck[52];
} test;
is this doable? the initialization of the deck (of cards) happens in a different function. when I do it like this, I don't get an error in the struct
but I get it when I try to use it... for example if I do this test.deck[i] = 1;
it gives me this error:
Error C2143 Syntax Error missing ';' before '.'
if I were to use a
, I could write test.a = 1;
Could anyone write a simple struct where a variable in it is an array and then just use it for a simple command?
If this is C++, no C, drop the test after the struct definition.
The following code works perfectly.
#include <iostream>
using namespace std;
struct Test {
int a;
int b;
int c;
int deck[52];
};
int main (int argc, char* argv[])
{
Test t;
t.deck[1] = 1;
cout << "t.deck[1]: "<< t.deck[1] << endl;
exit(0);
}
The problem: In C, you put the test after the definition to create a variable named test. So in C, test is not a type, it is a global variable , the way you wrote that.
This compiles:
#include <iostream>
using namespace std;
struct Test {
int a;
int b;
int c;
int deck[52];
} test;
int main (int argc, char* argv[])
{
test.deck[1] = 1;
cout << "test.deck[1]: "<< test.deck[1] << endl;
exit(0);
}
The error:
Error C2143 Syntax Error missing ';' before '.'
is due to test
being a type name. You need to define an instance:
int main() {
test mytest;
mytest.deck[1] = 1;
return 0;
}
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.