C ++中Struct中的数组

时间:2012-03-20 23:06:43

标签: c++

我一直在试图弄清楚如何将数组添加到结构中...例如,int的结构将如下所示:

struct test{
    int a;
    int b;
    int c;
} test = {0,1,2};

但是如果我想要一个数组,例如:

struct test{
    int a;
    int b;
    int c;
    int deck[52];
} test;

这可行吗?卡片(卡片)的初始化发生在不同的功能中。当我这样做时,我在struct中没有收到错误,但是当我尝试使用它时我得到它...例如,如果我这样做test.deck[i] = 1;它会给我这个错误:

Error C2143 Syntax Error missing ';' before '.'

如果我使用a,我可以写test.a = 1;

有人可以写一个简单的结构,其中的变量是一个数组,然后只用它来做一个简单的命令吗?

2 个答案:

答案 0 :(得分:3)

错误:

  

错误C2143语法错误';'在'。'之前。

是由于test是类型名称。您需要定义一个实例:

int main() {
   test mytest;
   mytest.deck[1] = 1;
   return 0;
}

答案 1 :(得分:3)

如果这是C ++,没有C,请在结构定义之后删除测试。

以下代码完美无缺。

#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);
}

问题:  在C中,您将测试放在定义之后,以创建名为test的变量。所以在C中,test是 not 一个类型,它是一个全局变量,就像你写的那样。

编译:

#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);
}