Thread: Allocating memory for a structure member

  1. #1
    Registered User dalek's Avatar
    Join Date
    May 2003
    Posts
    135

    Allocating memory for a structure member

    Hi

    I am new to C++ and obviously I have a few questions.

    Code:
    // If I declare a node like this
    typedef struct NODE
    {
    	int *data;
    	NODE *next;
    }Node;
    
    // And I have created a variable of this
    // type and allocated memory for it like this
    Node *rootp = new Node;
    
    // I understand I have to allocate 
    // Memory for the variable *data 
    // to use it..
    rootp->data = new int;
    rootp->data = 10;
    Now, I know there is a mistake above, but I am not sure why - my understanding of pointers is limited, I'm good if it is a single variable, but I get confused when I am face with structures or function arguments...

  2. #2
    Registered User dalek's Avatar
    Join Date
    May 2003
    Posts
    135
    Oh god - thanks.

    It's funny - I had that originally but under the debugger it was failing on that line every time..
    Code:
    rootp = NULL;
    rootp->data = new int;
    *rootp->data = 10;
    I guess it was failing because rather than pointing the rootp->next member to NULL I was pointing rootp to NULL, which would mean I was writing data nowhere?? Is that correct?

    Thanks for the help Salem.

  3. #3
    Registered User dalek's Avatar
    Join Date
    May 2003
    Posts
    135
    Cheers - I think I am learning!

    Thanks Salem.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Mutex and Shared Memory Segment Questions.
    By MadDog in forum Linux Programming
    Replies: 14
    Last Post: 06-20-2010, 04:04 AM
  2. Assignment Operator, Memory and Scope
    By SevenThunders in forum C++ Programming
    Replies: 47
    Last Post: 03-31-2008, 06:22 AM
  3. Question regarding Memory Leak
    By clegs in forum C++ Programming
    Replies: 29
    Last Post: 12-07-2007, 01:57 AM
  4. dynamic memory allocating error
    By valhall in forum C Programming
    Replies: 2
    Last Post: 04-04-2003, 10:49 AM
  5. Serial Communications in C
    By ExDigit in forum Windows Programming
    Replies: 7
    Last Post: 01-09-2002, 10:52 AM