Initialize an array within a struct
Hi all,
I'm implementing a list of arrays like so:
Code:
struct Cell {
int arrayValues[5];
Cell *next;
};
Cell *head;
How do I write the structure such that all arrayValues are set to 0? I'm trying to use a for loop
Code:
for(int i = 0; i < 5; i++)
head->valueArray[i] = 0;
outside of the struct but I'm not sure what I'm doing. Thanks for your help!
Re: Initialize an array within a struct
That is what constructors are for:
Code:
#include <iostream>
using namespace std;
struct Cell
{
Cell()
{
for(int i=0; i<5; ++i)
{
data[i] = 0;
}
next = 0;
}
int data[5];
Cell* next;
};
int main ()
{
Cell c; //This statement calls the constructor
cout<<c.data[4]<<endl; //0
cout<<">>>Hit Enter to Quit";
cin.get();
return 0;
}
You can accomplish the same thing outside the struct like this:
Code:
#include <iostream>
using namespace std;
struct Cell
{
int data[5];
Cell* next;
};
int main ()
{
Cell c;
for(int i=0; i<5; ++i)
{
c.data[i] = 0;
}
c.next = 0;
cout<<c.data[4]<<endl; //0
cout<<">>>Hit Enter to Quit";
cin.get();
return 0;
}
Re: Initialize an array within a struct
Ah, thanks a lot! I never knew about constructors in structs. Thanks again!
Re: Initialize an array within a struct
Quote:
Originally Posted by slicktacker
I never knew about constructors in structs.
C++ structs are exactly the same as C++ classes, with the tiny difference that the default visibility for struct members is public (private for class members).