在 C++ 中创建结构数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7239220/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 16:39:48  来源:igfitidea点击:

Creating an array of structs in C++

c++arraysstruct

提问by SnoringFrog

I'm working on an assignment that requires me to use an "array of structs". I did this once before for another assignment for this prof, using this code:

我正在处理一项要求我使用“结构数组”的作业。我之前为该教授的另一项作业做过一次,使用以下代码:

struct monthlyData {
    float rainfall;
    float highTemp; 
    float lowTemp;  
    float avgTemp;  
} month[12];

Which got the job done fine, but I got points marked off for the array being global. What should I do instead to avoid that? I haven't touched C++ at all over the summer, so I'm pretty rusty on it at the moment and have no clue where to start for this one.

这让工作做得很好,但我得到了标记为全局数组的分数。我应该怎么做才能避免这种情况?整个夏天我都没有接触过 C++,所以我现在对它很生疏,不知道从哪里开始。

回答by Nawaz

Simply define the struct as:

只需将结构定义为:

struct monthlyData {
    float rainfall;
    float highTemp; 
    float lowTemp;  
    float avgTemp;  
};

And then create an array of this struct, in a function, where you need it:

然后在需要它的函数中创建此结构的数组:

void f() {
    monthlyData month[12];
    //use month
}

Now the array is not a global variable. It is a local variable, and you've to pass this variable to other function(s) so that other function(s) can use the samearray. And here is how you should pass it:

现在数组不是全局变量。它是一个局部变量,您必须将此变量传递给其他函数,以便其他函数可以使用相同的数组。这是你应该如何通过它:

void otherFunction(monthlyData *month) {
    // process month
}

void f() {
    monthlyData month[12];
    // use month
    otherFunction(month);
}

Note that otherFunctionassumes that the size of array is 12(a constant value). If the size can be anything, then you can do this instead:

请注意,otherFunction假设数组的大小为12(常量值)。如果大小可以是任何大小,那么您可以这样做:

void otherFunction(monthlyData *month, int size) {
    // process month
}

void f() {
    monthlyData month[12];
    // use month
    otherFunction(month, 12); //pass 12 as size
}

回答by Davide Piras

well, you can have the array declared only inside the method that needs it :)

好吧,您只能在需要它的方法中声明数组:)

struct monthlyData
{
  float rainfall;
  float highTemp; 
  float lowTemp;  
  float avgTemp;  
};

int main()
{

  monthlyData month[12];

}

and if you need to use it also from another method, you pass it around as method parameter.

如果您还需要从另一个方法中使用它,则将它作为方法参数传递。

回答by Ed Heal

Declar the struct first

先声明结构体

struct monthlyData { 
   float rainfall; 
   float highTemp;  
   float lowTemp;   
   float avgTemp;   
};

Then use e.g.

然后使用例如

void foo()
{
   struct monthlyData months[12];
   ....

}