|
-
March 2nd, 2008, 11:51 PM
#1
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!
-
March 3rd, 2008, 01:16 AM
#2
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;
}
Last edited by 7stud; March 3rd, 2008 at 01:25 AM.
-
March 3rd, 2008, 01:23 AM
#3
Re: Initialize an array within a struct
Ah, thanks a lot! I never knew about constructors in structs. Thanks again!
-
March 3rd, 2008, 05:12 AM
#4
Re: Initialize an array within a struct
 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).
More computing sins are committed in the name of efficiency (without necessarily achieving it) than for any other single reason - including blind stupidity. --W.A.Wulf
Premature optimization is the root of all evil --Donald E. Knuth
Please read Information on posting before posting, especially the info on using [code] tags.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|