CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Mar 2008
    Posts
    4

    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!

  2. #2
    Join Date
    Oct 2004
    Posts
    296

    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.

  3. #3
    Join Date
    Mar 2008
    Posts
    4

    Re: Initialize an array within a struct

    Ah, thanks a lot! I never knew about constructors in structs. Thanks again!

  4. #4
    Join Date
    Jan 2004
    Location
    Düsseldorf, Germany
    Posts
    2,401

    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).
    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
  •  





Click Here to Expand Forum to Full Width

Featured