在c++中创建结构体数组
Creating an array of structs in C++
我正在做一个分配,要求我使用一个"结构体数组"。我以前为这个教授的另一个作业做过一次,使用以下代码:
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];
....
}
相关文章:
- 按结构体的特定成员对结构体数组进行排序
- 如何调用一个函数,它在一个单独的类中打印出一个结构体数组
- 如何创建一个结构体数组
- 初始化用于pthread的结构体数组
- 如何将文件的行读入结构体数组
- 结构体数组,非常量大小
- 无法将结构体数组传递给函数
- 确定它用作参数的结构体数组的大小
- 如何将结构体数组的单个成员数组传递给函数以执行线性搜索
- 如何使用std::binary_search或std::sort对结构体数组进行排序
- c++中对结构体数组使用排序选择
- 在c++中将结构体数组平整化为多个数组
- 在c++中创建结构体数组
- 不能操作由字符串组成的结构体数组
- 传递结构体数组的预期非限定id错误
- 将c++中的结构体数组传递给swift
- 尝试创建一个函数,将数据从文件读取到结构体数组中
- 在c++中创建结构体数组
- 添加并列出一个结构体数组
- Arduino编程中的结构体数组