![](/img/trans.png)
[英]How to initialize an int array within a struct within another struct arrya?
[英]How to search within an array thats within struct?
我在理解内存分配方面遇到了麻烦。
例如,如果我有一个结构如下:
struct AccountInfo{
int number;
int balance;
int past[9];
int minimum_past;
int maximum_past;
};
我如何访问past[9]
的数组? 一个更直接的问题是我如何找到past
的最小值和最大值,然后将这些值分配给minimum_past
和maximum_past
?
我理解将结构中的成员设置为某些值,我可以像AccountInfo -> number = 10;
那样做AccountInfo -> number = 10;
但是对于数组我还是很困惑。
我给你举了一个简单的例子。
在头文件中定义结构:
struct AccountInfo{
int number;
int balance;
int past[9];
int minimum_past;
int maximum_past;
};
在你的cpp文件中:
AccountInfo st_AccInfo;
访问您的结构:
int x = st_AccInfo.number;
for(int i=0; i<sizeof(st_AccInfo.past); i++)
{
// Navigate your Array from index 0 to 8
}
好吧,当您将past
声明为9个整数的数组时,就像从0开始的C ++计数索引一样,在不调用未定义行为的情况下可以使用的索引越大,为8。
话虽如此,您使用与其他struct元素完全相同的数组元素:
AccountInfo accountInfo; // create a struct
AccountInfo* paccountInfo = &accountInfo; // define a pointer to it
accountInfo.last[8] = 12; // direct access
cout << paccountInfo->last[8] << endl; // access through pointer - outputs 12
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.