Thread: Trying to Understand Structure

  1. #1
    Registered User
    Join Date
    Aug 2005
    Posts
    80

    Trying to Understand Structure

    I'm still pretty new to C and still do not have a good grasp on pointers and structures.

    I'm working on a program that globally declares a nested? structure, and globally declares another structure that I believe is related:

    Code:
    static struct alist {         /*  Nodes of linked list: Paths */
       int *p;                    /*  Array of paths              */
       struct alist *Next;        /*  Next path                   */
    };
    
    static struct alist **Saved;        /* Saved paths               */
    There is a function named ev_num that does something with these functions:
    Code:
    Saved =  (struct alist **) malloc(sizeof(struct alist*));   
      *Saved = (struct alist *)NULL;    /* Linked list of saved paths */
    
     GetPath( m, r );                  /* Get the paths */
    Does anyone understand what' going on with the above code? Any help would be appreciated because I'm pretty lost.

    Basically, how would I go about getting values out of this structure?
    Last edited by jamez05; 09-28-2006 at 09:43 AM.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    The first thing is to remove all those redundant casts on assigning the result of malloc, and assigning NULL (this is C after all)

    Given say
    struct alist *foo = *saved;

    Then you could do
    foo->p[0] = 0;
    to access the first element of your array

    and
    foo = foo->Next;
    to advance to the next node.

    This is typical for traversing linked lists
    Code:
    while ( foo != NULL ) {
      // do stuff
      foo = foo->Next;
    }
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    System Novice siavoshkc's Avatar
    Join Date
    Jan 2006
    Location
    Tehran
    Posts
    1,246
    This kind of learning is a bad practice. Try learning by a good book or tutorial step by step.
    Learn C++ (C++ Books, C Books, FAQ, Forum Search)
    Code painter latest version on sourceforge DOWNLOAD NOW!
    Download FSB Data Integrity Tester.
    Siavosh K C

  4. #4
    Registered User
    Join Date
    Aug 2005
    Posts
    80

    Thanks for your feedback

    Thanks Salem, that helped me get a better grasp on it. I'll look into a good C++ book as well.

Popular pages Recent additions subscribe to a feed