Creating an array of structs in C++

橙三吉。 提交于 2019-12-30 10:54:07

问题


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.


回答1:


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 same array. 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 otherFunction assumes that the size of array is 12 (a constant value). If the size can be anything, then you can do this instead:

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

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



回答2:


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.




回答3:


Declar the struct first

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

Then use e.g.

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

}


来源:https://stackoverflow.com/questions/7239220/creating-an-array-of-structs-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!