Thread: malloc for tree structures

  1. #1
    Registered User
    Join Date
    Oct 2007

    malloc for tree structures


    I have a tree structure defined as.

    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
    Registered User
    Join Date
    Sep 2007
    Each time you need a node, you allocate it:
    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, 03:05 AM
  2. pointers, structures, and malloc
    By lugnut in forum C Programming
    Replies: 24
    Last Post: 10-09-2008, 04: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, 12:59 PM