malloc for tree structures

This is a discussion on malloc for tree structures within the C Programming forums, part of the General Programming Boards category; Hi, I have a tree structure defined as. Code: typedefchar value [50]; typedef struct tree*node; struct tree { node l, ...

  1. #1
    Registered User
    Join Date
    Oct 2007
    Posts
    1

    malloc for tree structures

    Hi,

    I have a tree structure defined as.

    Code:
    typedefchar value [50];
    typedef struct tree*node;
    struct tree {
             node l, r;
             value setvalue;
    };
    I am aware that in C you have to allocate memory for the structure, or you get a segmentation error.
    Should I allocate memory to each part of the structure or should I allocate memory to the whole structure?
    how do I allocate memory in this case? (example code would be nice)

  2. #2
    cas
    cas is offline
    Registered User
    Join Date
    Sep 2007
    Posts
    993
    Each time you need a node, you allocate it:
    Code:
    struct tree *root;
    root = malloc(sizeof *root);
    if(root == NULL) { /* do something on error */ }
    root->l = NULL;
    root->r = NULL;
    strcpy(root->setvalue, "I am a node");
    When you need to add a node, you allocate a new one like you did for the root and then point l or r to it. It's a little more complex than that (you have to traverse the tree to find the proper node) but since you're working with trees, you presumably understand that.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. malloc, structures, arrays and sudoku!!
    By AmbliKai in forum C Programming
    Replies: 13
    Last Post: 10-15-2008, 04:05 AM
  2. pointers, structures, and malloc
    By lugnut in forum C Programming
    Replies: 24
    Last Post: 10-09-2008, 05:52 PM
  3. Structures, arrays, pointers, malloc.
    By omnificient in forum C Programming
    Replies: 9
    Last Post: 02-29-2008, 12:05 PM
  4. malloc ing array's or structures
    By Markallen85 in forum C Programming
    Replies: 4
    Last Post: 02-03-2003, 01:23 PM
  5. Methods for Sorting Structures by Element...
    By Sebastiani in forum C Programming
    Replies: 9
    Last Post: 09-14-2001, 01:59 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21