在c++中创建结构体数组

Creating an array of structs in C++

本文关键字:结构体 数组 创建 c++      更新时间:2023-10-16

我正在做一个分配,要求我使用一个"结构体数组"。我以前为这个教授的另一个作业做过一次,使用以下代码:

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

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

简单定义结构体为:

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

然后在需要的函数中创建该结构体的数组:

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

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

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

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

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

好吧,你可以只在需要它的方法中声明数组:)

struct monthlyData
{
  float rainfall;
  float highTemp; 
  float lowTemp;  
  float avgTemp;  
};
int main()
{
  monthlyData month[12];
}

,如果你需要在另一个方法中使用它,你可以把它作为方法参数传递。

先声明结构体

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

然后用例如

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