Thread: Array of Structs - How do you move to the next struct in the array?

  1. #1
    Registered User
    Join Date
    Nov 2005
    Posts
    41

    Array of Structs - How do you move to the next struct in the array?

    Hi,

    Let's say I have an array of structs.
    How do I move through the array to retrieve the next struct in list?

    Please advise. Thanks
    If I'm able to turn back time, I would learn C as my first language.

  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
    Same as any other array - a for loop and an index ought to do it.

  3. #3
    Registered User
    Join Date
    Nov 2005
    Posts
    41
    But I can't seems to iterate through it.

    What I intend to do is have a function that will loop through the linked list; collect all the structs and store them in an array.

    This function will return the array of structs.

    Then I can call the function and make use of the array of structs when neccessary.

    Code:
    node *ShowAllNodes()
    {
     node *curr=NULL;
     node *arr[256];
     int i;
     curr=FirstNode;
     while(curr)
     {
      arr[i]=curr;
      curr=curr->Prev;
     }
     return *arr; 
    }
    Then assuming I have stored data into the list, i attempted to try and make use of the data.

    Code:
    node *results=NULL;
    ..
    ..
    ..
             results=ShowAllNodes();
               printf("%s\n",results[0]->IC);  /*This 2 lines hits compilation erro*/
               printf("%s\n",results[1]->IC);  /**/


    Please advise. Thanks
    If I'm able to turn back time, I would learn C as my first language.

  4. #4
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    It's an array, not a linked list. (Or maybe it's both, you just haven't set it up that way perhaps.) Do you know how to walk through a string? Do the same thing, but keep in mind you're using structures instead of characters:
    Code:
    for( x = 0; x < size; x++ )
    {
        array[ x ].something = foo;
        bar = array[ x ].somethingelse;
    }
    Or, you could use a pointer:
    Code:
    nodeptr = array;
    ...do fun stuff...
    nodeptr++; <-- move to the next array element

    Quzah.
    Hope is the first step on the road to disappointment.

  5. #5
    Registered User
    Join Date
    Nov 2005
    Posts
    41
    Thanks Salem and Quzah

    After some reading up, I came out with the following:

    Code:
    node **ShowAllNodes()
    {
     node *curr = NULL;
     node **RtnValues=NULL;
     int i=0;
     curr = LastNode;
     while(curr)
     {
      RtnValues[i]=malloc(sizeof(node)); /*this line will cause it to crash*/
      if(RtnValues[i]==NULL) /*this line too! */
      {
       printf("bah!!"); /*i dont even hav chance to see it print "bah"!"*/
       exit(1);
      }
      RtnValues[i]->id=curr->id; /*this line will cause it to craash too.*/
      strcpy(RtnValues[i]->IC,curr->IC);    /*this line will cause it to craash too.*/
      curr = curr->Next;
      i++;
     }
     return RtnValues;
    }
    Code:
    node **results=NULL;
    ..
    ..
    ..
             results=ShowAllNodes();
          printf("%i\n", results[0]->id);
          printf("%s", results[0]->IC);
    But the program will crash whenever it hits any lines with "RtnValues[i]"

    What would possible went wrong?
    Last edited by stevong; 12-06-2005 at 09:46 AM.
    If I'm able to turn back time, I would learn C as my first language.

  6. #6
    Registered User
    Join Date
    Nov 2005
    Posts
    41
    I came up with something "similiar". And it works fine. Im puzzled.

    Code:
    person **testing()
    {
      person **test;
       test[0] = malloc(sizeof(person));
       test[1] = malloc(sizeof(person));
       test[0]->name="ONE";
       test[1]->name="TWO";
       
       return test;
    }
    
    int main()
    {
     person **ptr;
     ptr=testing();
     printf("%s\n",ptr[0]->name);
     printf("%s",ptr[1]->name);
     getchar();
     
     return 0;
    }
    If I'm able to turn back time, I would learn C as my first language.

  7. #7
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    You lucked out. You have no 'test[0]' and 'test[1]', because you didn't allocate any pointers. I don't know why you're using a set of double pointers there. You just need one.
    Code:
    struct node *list;
    struct node *ptr;
    size_t x;
    
    list = malloc( N * sizeof( struct node )  ); /* allocate an 'array' of N nodes */
    if( !list )
    {
        abandonship( );
    }
    
    for( ptr = list; ptr < list + N; ptr++ )
    {
        ... do something with this node ...
    }
    
    for( x = 0; x < N; x++ )
    {
        list[ x ].dosomethingwithme = dosomethinghere( );
    }
    
    free( list );
    Quzah.
    Hope is the first step on the road to disappointment.

  8. #8
    Registered User
    Join Date
    Nov 2005
    Posts
    41
    Quote Originally Posted by quzah
    You lucked out. You have no 'test[0]' and 'test[1]', because you didn't allocate any pointers. I don't know why you're using a set of double pointers there. You just need one

    Quzah.
    *blushed*
    I often used trial and error to venture into new territories and trying out new stuffs. =p My luck indeed ran out. haha.

    I've used pointer to pointer because

    **ptr is the same as *ptr[] ?

    Pointer to array of strings.. So i thought the concept should be similiar with structs?

    I believe not many agree with trial and error. Programming requires full understanding of the things you are playing with. That's the difference between a rookie and seasoned professionals I supposed
    If I'm able to turn back time, I would learn C as my first language.

  9. #9
    Registered User cbastard's Avatar
    Join Date
    Jul 2005
    Location
    India
    Posts
    167
    I've used pointer to pointer because

    **ptr is the same as *ptr[] ?
    NO, its not.
    Long time no C. I need to learn the language again.
    Help a man when he is in trouble and he will remember you when he is in trouble again.
    You learn in life when you lose.
    Complex problems have simple, easy to understand wrong answers.
    "A ship in the harbour is safe, but that's not what ships are built
    for"

  10. #10
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    I'm puzzled as to why something called showallnodes should need to call malloc, or why it seems to start at the last node of the list.

  11. #11
    Registered User
    Join Date
    Nov 2005
    Posts
    41
    Quote Originally Posted by Salem
    I'm puzzled as to why something called showallnodes should need to call malloc, or why it seems to start at the last node of the list.
    My concepts on memory alloc and pointers are still totally screwed. Im confusing myself at times. (I feel guilty posting all these threads at times)

    Ok, here's the oringinal show all nodes, which i feel it's not very useful since it only prints out onto the screen:

    Code:
    void ShowAllNodes()
    {
     node *curr = NULL;
    
     curr = LastNode;
     while(curr)
     {
      printf("   %i",curr->id);
      printf("   %s",curr->IC);
      printf("\n");
      curr = curr->Next;
     }
    }
    The above showallnodes do not require malloc is because memory is already allocated in the Add Node functions. It's job is just to output to the screen.

    So I thought: Why not write a function which returns all the items and values in the link list and use a variable to keep hold of it; then I would use it whenever I want...and the result is: This thread..

    Why I malloc in showallnodes is because, erm, need memory space to keep the information? then this info can be returned to the user.
    Last edited by stevong; 12-06-2005 at 12:48 PM.
    If I'm able to turn back time, I would learn C as my first language.

  12. #12
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,218
    I'm not sure of the point, unless you're just looking for a way to quickly access nodes in your linked list by index. I've used a similar method before by creating an array of pointers to my linked list nodes. That way I could walk through all of the nodes quickly by using the linked list, or I could randomly access a node in the linked list quickly by index instead of having to walk to it through the linked list. In order to maintain integrity I'd set my array elements to NULL for deleted nodes.

    Am I totally off on your intentions?
    If you understand what you're doing, you're not learning anything.

  13. #13
    Registered User
    Join Date
    Nov 2005
    Posts
    41
    Quote Originally Posted by itsme86
    I'm not sure of the point, unless you're just looking for a way to quickly access nodes in your linked list by index. I've used a similar method before by creating an array of pointers to my linked list nodes. That way I could walk through all of the nodes quickly by using the linked list, or I could randomly access a node in the linked list quickly by index instead of having to walk to it through the linked list. In order to maintain integrity I'd set my array elements to NULL for deleted nodes.

    Am I totally off on your intentions?
    You meant, something similiar to this? My struct has a member int which auto increment by one...


    Code:
    node *GetNode(int idx)
    {
     node *curr = NULL;
     curr=LastNode;
     while(curr)
     {
      if(idx==curr->id)return curr;
      curr=curr->Next;
     }
    }
    RecordCount is a function which loops thru the list to calculate the number of nodes in the list..

    Code:
             rc=RecordCount();
             for(c=0;c<rc;c++)
             {
              singlenode=GetNode(c);        
              printf("%s\n",singlenode->IC);
             }
    If I'm able to turn back time, I would learn C as my first language.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. memory issue
    By t014y in forum C Programming
    Replies: 2
    Last Post: 02-21-2009, 12:37 AM
  2. towers of hanoi problem
    By aik_21 in forum C Programming
    Replies: 1
    Last Post: 10-02-2004, 01:34 PM
  3. Bi-Directional Linked Lists
    By Thantos in forum C Programming
    Replies: 6
    Last Post: 12-11-2003, 10:24 AM
  4. Contest Results - May 27, 2002
    By ygfperson in forum A Brief History of Cprogramming.com
    Replies: 18
    Last Post: 06-18-2002, 01:27 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