Thread: Array of Pointers to Structs

  1. #1
    Registered User
    Join Date
    Sep 2006
    Posts
    25

    Array of Pointers to Structs

    Every once in a while, I mean year, I need to create an Array of Pointers to Structs (at runtime - user defined size) and i can NEVER remember how to do it and my reference book example doesnt seem to help me too much. So, I made a test prog to do so yet it blows up on me at the end. What am i missing... this time?
    Code:
    #include <iostream>
    using namespace std;
    
    struct node
    {
    	int n;
    	node * ptrnode;
    	node(){n = 0; ptrnode = NULL;}
    };
    
    class Obj
    {
    public:
    	Obj(){size = 0; root = NULL;}
    	Obj(int i)
    	{
    		size = i; 
    		root->ptrnode = new node[i];
    	}
    //private:
    	int size;
    	node * root;
    };
    
    
    int main()
    {
    	int i;
    	cout<<"create number: ";
    	cin>> i;
    	Obj test(i);
    	cout << "Size is " << test.size;
    	return 0;
    }
    Last edited by I BLcK I; 03-15-2008 at 10:49 PM.

  2. #2
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    In the constructor Obj (int i), root is not initialised to point at anything valid, but root->ptrnode is assigned to. That causes undefined behaviour.

  3. #3
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    One day you'll learn about std::vector.

    Until that day comes, you should remember that in your constructor of Obj, you want to set root to be a pointer to an array, not root->ptrnode. (Unless you're trying to set a linked list, but you wouldn't do that in advance, so that can't be what you mean.)

  4. #4
    Registered User
    Join Date
    Sep 2006
    Posts
    25
    Thnxs. I gotta engrave this into my head somehow.

    EDIT: heh i just read about the mention of "vector" in my book. It does sounds like it will make things a lot easier, but i dont wanna keep on forgetting the basics which i tend to do quite often :/
    Last edited by I BLcK I; 03-15-2008 at 11:06 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. MergeSort with array of pointers
    By lionheart in forum C Programming
    Replies: 18
    Last Post: 08-01-2008, 10:23 AM
  2. array of pointers to an array pointers
    By onebrother in forum C Programming
    Replies: 2
    Last Post: 07-28-2008, 11:45 AM
  3. Creating an array of pointers to int[]
    By OkashiiKen in forum C Programming
    Replies: 3
    Last Post: 09-29-2006, 06:48 PM
  4. Struct *** initialization
    By Saravanan in forum C Programming
    Replies: 20
    Last Post: 10-09-2003, 12:04 PM
  5. Hi, could someone help me with arrays?
    By goodn in forum C Programming
    Replies: 20
    Last Post: 10-18-2001, 09:48 AM