Thread: Structures - Linked List

  1. #1
    Registered User
    Join Date
    Jun 2011
    Posts
    41

    Structures - Linked List

    I have 3 structures:

    The first one is an array, which needs to point to class_node in order to make a list. I am not sure how to approach this. I've reviewed all the web tutorials, the book etc and running into issues trying to organize this.

    Code:
    struct studentReg {
           int studentID;
           char lastName[20];
           char firstName[20];
           char phoneNumber[20];
           struct classed *listPtr; //This should be a pointer to class_Node ?? yes
    } structArray[NUM_STUDENTS];
    
    typedef struct class_node {
           int studentID;
           char course[7];
           int section;
           struct class_node *next; // points to next node
    } class_Node;
    
    struct Courses {
           char course[7];
           int section;
           int creditHours;
    } coursesArray[NUM_OF_COURSES];
    All of the info is being pulled from text files which will be populated into the appropriate structures.

    studentReg points to class_node and class_node expands depending on how many class the student is registered to. The other structure is for testing purposes to ensure the classes are accurate.

    Also any tips on making this more fluent and easier to understand would be great. If the code is incorrect please feel free to yell at me and tell me what i'm doing wrong!

  2. #2
    Registered User
    Join Date
    May 2011
    Location
    Around 8.3 light-minutes from the Sun
    Posts
    1,949
    Well, right off the bat your code won't compile. Is this just a paste typo?:
    Code:
    char phoneNumber[20];
    struct classed *listPtr; //This should be a pointer to class_Node ?? yes
    Shouldn't this be class_Node?

    Second, C only knows about things it sees in a top down order. So when you try to reference class_Node in your studentReg structure it will throw an error. You need to move the class_Node structure to before the studentReg structure.

    Take a look at this thread. There was a good discussion of linked lists there. Scroll down to the big explaination.
    Last edited by AndrewHunter; 07-14-2011 at 12:51 AM.
    Quote Originally Posted by anduril462 View Post
    Now, please, for the love of all things good and holy, think about what you're doing! Don't just run around willy-nilly, coding like a drunk two-year-old....
    Quote Originally Posted by quzah View Post
    ..... Just don't be surprised when I say you aren't using standard C anymore, and as such,are off in your own little universe that I will completely disregard.
    Warning: Some or all of my posted code may be non-standard and as such should not be used and in no case looked at.

  3. #3
    Registered User
    Join Date
    Jun 2011
    Posts
    41
    Ok, after trying to digest that code I'm still sorta lost, as is my partner.

    Maybe we just aren't grasping some feature.

    Here is the reworked code:

    Code:
    typedef struct class_node {
           int studentID;
           char course[7];
           int section;
           struct class_node *nextNode;
    } class_Node;
    
    class_Node classesArray[NUM_OF_CLASSES];
    class_Node *nextNode = NULL;
    
    struct studentReg {
           int studentID;
           char lastName[20];
           char firstName[20];
           char phoneNumber[20];
           class_Node *first; 
    } structArray[NUM_STUDENTS];
     
    struct Courses {
           char course[7];
           int section;
           int creditHours;
    } coursesArray[NUM_OF_COURSES];

    now, strudentReg is an array of struct's. We have 20 elements for example. Each element has a linked list of X classes all of which point to the next on in the link. (Class_node). Now, we instantiated all the info into studentReg, but not sure how to attach the struct class_node to that list properly.

    once we figure that, we feel confident that we will be able to do the linked list part. from the example in the link you provided. Thanks for any help. Hope I am not frustrating anyone with my questions / lack of experience

  4. #4
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    I don't know what you think you mean by "attach the struct class_node to the list". You've embedded a list (or perhaps more properly, a pointer to the first element of your list, but that's a distinction without a difference) inside your struct.

  5. #5
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Look at your structs... you have a lot of duplicated information between them... Why not just combine them all into a single struct and make your code a whole lot simpler?

    Hints: Yes you can put arrays in structs. Yes it will be easier to sort and search. No what you have is not efficient storage.

    Think about a school with 10,000 students... how you going to work that with your current setup?

  6. #6
    Registered User
    Join Date
    Jun 2011
    Posts
    41
    We need to have an array of structures holding all the students info, and a structure linked list of the students classes he's enrolled in.

    The third structure isn't mandatory, it is something we are working with for validation.

    If that makes sense. This is a guideline he gave us for the project for our class.

    If you have a better / more simplistic form to do what we are trying to achieve I am all ears

  7. #7
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Code:
    yourarray[ thisguy ].firstclassptr = nodeptr;

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

  8. #8
    Registered User
    Join Date
    May 2011
    Location
    Around 8.3 light-minutes from the Sun
    Posts
    1,949
    Before we start, I am going to come out and say I agree with Tater on this one. Unless you are just playing around with linked lists for practice there is no reason to implement this solution like this.

    Now let's take a look:

    Quote Originally Posted by Oonej View Post
    now, strudentReg is an array of struct's. We have 20 elements for example. Each element has a linked list of X classes all of which point to the next on in the link. (Class_node). Now, we instantiated all the info into studentReg, but not sure how to attach the struct class_node to that list properly.
    Code:
    typedef struct class_node {
           int studentID;
           char course[7];
           int section;
           struct class_node *nextNode; //this implements the link in your list
    } class_Node;
    //this is not needed at all
    class_Node classesArray[NUM_OF_CLASSES];
    class_Node *nextNode = NULL;
    
    struct studentReg {
           int studentID;
           char lastName[20];
           char firstName[20];
           char phoneNumber[20];
           class_Node *first;//this anchors and starts your linked list of class_Nodes 
    } structArray[NUM_STUDENTS];
    //you still haven't done anything with this yet 
    struct Courses {
           char course[7];
           int section;
           int creditHours;
    } coursesArray[NUM_OF_COURSES];
    And that is about it.
    Last edited by AndrewHunter; 07-14-2011 at 04:45 PM.
    Quote Originally Posted by anduril462 View Post
    Now, please, for the love of all things good and holy, think about what you're doing! Don't just run around willy-nilly, coding like a drunk two-year-old....
    Quote Originally Posted by quzah View Post
    ..... Just don't be surprised when I say you aren't using standard C anymore, and as such,are off in your own little universe that I will completely disregard.
    Warning: Some or all of my posted code may be non-standard and as such should not be used and in no case looked at.

  9. #9
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by Oonej View Post
    We need to have an array of structures holding all the students info, and a structure linked list of the students classes he's enrolled in.

    The third structure isn't mandatory, it is something we are working with for validation.

    If that makes sense. This is a guideline he gave us for the project for our class.

    If you have a better / more simplistic form to do what we are trying to achieve I am all ears
    Welllll... for starts I would never approach a problem like this as a linked list nor would I attempt to have more than one student record in memory at a time. There are structured binary file techniques (most often called "Random Access Files") that would let you write and read entire structs to disk ( fread() and fwrite() ) entirely eliminating the need for huge in-memory lists. One simple struct would do the whole job... To read or write that struct it's a matter of using fseek() to position your file pointer to the beginning of a struct on disk, reading it into memory... doing what you needed to do... repositioning and writing it back out. You would never have to load that entire file, sort it or write huge arrays to disk. Moreover, random access techniques will probably reduce your code size significantly and run considerably faster than linked lists.

    How to Work with Random Access Files


    (Hint: The mistake many make is to think they have to have everything in memory at once... In fact all you need in memory at any one time is the one record (struct) you are working on.)
    Last edited by CommonTater; 07-14-2011 at 04:57 PM.

  10. #10
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Ok, here's a tiny bit of code I cooked up to show just how simple random access files can be...
    Code:
    //random access file demo
    #include <stdlib.h>
    #include <stdio.h>
    #include <time.h>
    #include <string.h>
    
    #define FNAME "random.dat"
    
    // test data struct
    struct t_Record
      { int randnum;
        char word[16]; }
      Record;
    
    
    
    ///////////////////////////////////////////////////////
    // Random Access File Handlers
    //
    
    // open or create the file
    FILE *FileOpen(char* Filename)
      { FILE* pFile;
        pFile = fopen(Filename,"rb+");
        if (!pFile)
          pFile = fopen(Filename,"wb+");
        return pFile; }
    
    
    // Write a record to the file
    int WriteRecord(FILE *File, int RecNum)
      { if( fseek(File, RecNum * sizeof(Record), SEEK_SET) == 0 )
          if ( fwrite(&Record,sizeof(Record),1,File) )
            return 1;
        return 0; }
    
    
    // read a record from the file
    int ReadRecord(FILE *File, int RecNum)
      { if( fseek(File, RecNum * sizeof(Record), SEEK_SET) == 0 )
          if ( fread(&Record,sizeof(Record),1,File) )
            return 1;
        return 0; }
    
    
    
    ////////////////////////////////////////////////////////
    // this is for demonstration purposes only
    // you would not do this in a real program
    void InitFile(FILE* File)
     { int x, y;
       memset(&Record,sizeof(Record),0);
       for (x = 0; x < 1000; x++)
          { Record.randnum = rand();
            for (y = 0; y < ((Record.randnum % 15) + 1); y++)
              Record.word[y] = (rand() % 26) + 'a';
            if (! WriteRecord(File,x))
              printf("Oh drat!");  } }
     
    
     
    //////////////////////////////////////////////////////////
    // program mains
    //
    int main (void)
      { FILE *File;
        int Quit = 0;
        int Rec = 0; // record number
    
        srand(time(NULL));
    
        File = FileOpen(FNAME); 
        if (!File)
          { printf("Curses foiled again!\n\n");
            exit(-1); }
    
        // write out 1000 test records  
        printf("Create a new file? (y/n)  ");
        if ( toupper( getchar() ) == 'Y')
          InitFile(File);
      
        // lets peek
        do
          { printf("Enter a record number (0 - 999) to load : ");
            if (! scanf("%d",&Rec) )
              Quit = 1;  // enter any letter to quit
            else 
              { // read and display the record 
               if (! ReadRecord(File,Rec) ) 
                  printf("Could not read record %d\n",Rec);
                else
                  { printf("-----\n");
                    printf("Record Number : %d\n",Rec);
                    printf("Number Value  : %d\n",Record.randnum);
                    printf("Record Name   : %s\n",Record.word);
                    printf("-----\n"); 
                    getchar();
                    printf("Do you want to rename this record (y/n)? ");
                    if ( toupper( getchar() ) == 'Y')
                      { printf("Enter a new name : ");
                        if ( scanf("%s",Record.word) )
                          WriteRecord(File,Rec);  } } }
          } while (! Quit); 
    
    
        fclose(File);
        return 0; }
    Please note how simple the file i/o is and how easily a record can be changed and replaced in the file. Also note that only one record is ever loaded at a time... no arrays, no malloc, no complicated linked lists...

  11. #11
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Globals? Really? :sadtuba:

    Speaking of Pascal... that's where I first used random access files I think. It was so easy to do.


    Quzah.
    Last edited by quzah; 07-14-2011 at 09:12 PM. Reason: no :eyebrow: smiley? How about sad tuba then?
    Hope is the first step on the road to disappointment.

  12. #12
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by quzah View Post
    Globals? Really? :eyebrow:
    Quzah.
    I often use a global struct with random access files... it's a lot easier than passing it around in virtually every function.

    But yes... I know...

    (p.s. ... Can't you find something good to say about it? )

  13. #13
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Quote Originally Posted by CommonTater View Post
    (p.s. ... Can't you find something good to say about it? )
    Looking at it reminded me of records in Pascal. Good times. I know everyone's a fan of text files for records here, but I like random access files for records. Maybe not for everything, but they have their place, and I don't care if someone wants to cry about non-portability. Not everything in the world has to be, or is portable -- actually it is, so long as you are given the file format, like I argued before; go look at .PNG or any other file extension of your choosing.


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

  14. #14
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Ahhh Pascal... those were the days!

    Effing Borland just had to kill it!


    I've never understood this whole "human readable" thing that seems to fire the text file fans... When's the last time a user opened a data file and looked inside? And why do they have to be able to read it even if they do?

  15. #15
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Quote Originally Posted by CommonTater View Post
    I've never understood this whole "human readable" thing that seems to fire the text file fans... When's the last time a user opened a data file and looked inside? And why do they have to be able to read it even if they do?
    I find myself often disappointed when I open a .bmp in a text editor and there are no pretty pictures waiting for me...


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

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Structure of structures + linked list
    By saeculum in forum C Programming
    Replies: 3
    Last Post: 03-06-2009, 08:02 PM
  2. single linked list to double linked list (help)
    By Countfog in forum C Programming
    Replies: 8
    Last Post: 04-29-2008, 08:04 PM
  3. singly linked list to doubly linked list
    By t48j in forum C Programming
    Replies: 3
    Last Post: 03-23-2005, 06:37 PM
  4. Replies: 6
    Last Post: 03-02-2005, 02:45 AM
  5. problem with structures and linked list
    By Gkitty in forum C Programming
    Replies: 6
    Last Post: 12-12-2002, 06:40 PM