Creating an array of structures in C ++

I am working on an assignment that requires me to use an "array of structures". I did this once before for another assignment for this professor using this code:

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

Which got the job done, but I got points marked so that the array is global. What should I do to avoid this? I didn't touch C ++ at all in the summer, so at the moment I'm pretty rusty, and I don't know where to start this.

+3
source share
3 answers

Just define the structure as:

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

And then create an array of this structure in the function where you need it:

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
}
+4

, , :)

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

int main()
{

  monthlyData month[12];

}

, .

+2

Declare structure first

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

Then use for example

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

}
0
source

All Articles