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];
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
}