I am trying to loop through a struct array and initialize its member "history
", an int array, to 0
(Undoubtedly, you'll have a better suggestion than the one-value-at-a-time loop, which will be welcome, but that's not what the question is about).
I get an error not only I do not understand, but I cannot see how the multiple internet posts about it come into a function within my case.
The error is:
In function 'int main()':....
|error: request for member 'history' in 'coin', which is of non-class type 'coin_t [10]'|
This is my code (true copy-paste from a new project):
#include <iostream>
using namespace std;
// Hand input parameters
const int coinCount=10;
int weight[coinCount]={11,11,9,10,10,10,10,10,10,10};
const int maxDepth=6;
const int caseCount=360;
// GLOBALS
struct coin_t
{
float w;
int history[maxDepth];
int curDepth;
};
coin_t coin[coinCount];
int main()
{
int i,j;
//Initialize coin struct array
for(i=0;i<coinCount;i++)
{
coin[i].w=weight[i];
coin[i].curDepth=-1;
for(j=0;j<maxDepth;j++) coin.history[j]=0; // Here's the error
}
}
coin
is an array of struct coin_t
with sized coinCount
. You need to access by operator[]
for the corresponding element in the array.
coin[i].history[j] = 0;
// ^^^
If you want to zero-initialize the history
you could do better
struct coin_t
{
float w;
int history[maxDepth]{0};
// ^^^^
int curDepth;
};
by which you can skip the extra looping
for (j = 0; j < maxDepth; j++)
coin[j].history[j] = 0;
That being said C++ offers better std::array
. Consider use if its suitable to the case.