Click to See Complete Forum and Search --> : Initialize an array within a struct
slicktacker
March 2nd, 2008, 10:51 PM
Hi all,
I'm implementing a list of arrays like so:
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
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!
7stud
March 3rd, 2008, 12:16 AM
That is what constructors are for:
#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:
#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;
}
slicktacker
March 3rd, 2008, 12:23 AM
Ah, thanks a lot! I never knew about constructors in structs. Thanks again!
treuss
March 3rd, 2008, 04:12 AM
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).
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.