linked list inside array of structs- Syntax question

This is a discussion on linked list inside array of structs- Syntax question within the C Programming forums, part of the General Programming Boards category; I have a linked list inside an array of structs: Code: typedef struct Course { char Number [NumSize + 1]; ...

  1. #1
    Registered User
    Join Date
    Feb 2005
    Posts
    10

    Question linked list inside array of structs- Syntax question

    I have a linked list inside an array of structs:
    Code:
    typedef struct Course {
    char Number [NumSize + 1]; 
    char Section [SecSize + 1]; 
    int Units;   
    struct Course *Next; 
    } Course_T; 
    
    typedef struct Stud {       
        char SSN[SSNsize+1];   
        char Class;                   
        float GPA;                    
        int Units;         
        int NumCourses; 
        Course_T* CourseList; 
        } Student_T;         
    Student_T StudentList[ListMax];
    My question is, when I go to print out the contents of each array member, what is the syntax of printing out the linked list contents with them?

    Heres the whole mess so far, no error correction etc.

    Code:
    #include <ctype.h>
    #include <stdlib.h>
    #include <stdio.h>
    #include <string.h>       /* for string comparisons */
    #define False 0                /*False indicator*/
    #define NotFound -1         /* indicator for student not found in list */
    #define SSNsize 11          /* Size of SSN string */
    #define ListMax 100        /* student list max length */
    #define LineLength 80          /* Max length of input line */
    #define NumSize 5  /*Max Length of Course Number*/
    #define SecSize 3  /*Max Length of Section Number*/
    
    typedef struct Course {
    char Number [NumSize + 1]; /*Course Number*/
    char Section [SecSize + 1]; /*Course Section*/
    int Units;   /*Course Credits*/
    struct Course *Next; /*Next Course pointer*/
    } Course_T; 
    
    typedef struct Stud {           /* Student Records */
        char SSN[SSNsize+1];        /* SS# array of char */
        char Class;                 /* Student Classification */
        float GPA;                  /* Grade Point Average */
        int Units;                /* # of units */
        int NumCourses; /* Number of classes being taken */ 
        Course_T* CourseList; /* Ptr to list of classes */ 
        } Student_T;         /* Struct Type of Student*/
    Student_T StudentList[ListMax];      /* list of student data */
    /********************************/
    main()
    {
    /* Start of Function prototypes */
      int ReadList (Student_T*, char*);        
      void DisplayStudent (int StudentNum, Student_T* StudentList);
     /* End of Function prototypes */
      char File[LineLength];
      int StudentNum;   /* Number of students in array at start */
      char response;    /* Menu Choice response */
      int Index = 0;    /* position of student file found in array */
       /** Beginning of Program **/
      StudentNum = ReadList (StudentList,File);    /* Pass address of 1st element of array */
                                                     /* Return # of records read into array */
      DisplayStudent(StudentNum,StudentList);
      system("PAUSE");
          return 0;
    }
    /*************************************************************/
    int ReadList (Student_T *StudentList, char *name)
    {
      char line[LineLength+1];      /* Line read from file */
      int CurrNum = 0;           /* Index into array for current student */
      char filename[LineLength];    /* Data file name */
      int i;
      FILE *data;                /* Data file pointer */
      Student_T *Curr;            /* Pointer to current student (student being read) */
      Course_T  *New, /* Used to allocate memory for new nodes */       
      *First = NULL, /* Ptr to First node in list */       
      *Last = NULL; /* Ptr to Last node in list */ 
      /* First and Last set to NULL to indicate empty list */ 
       
      do
      {
      printf ("\nEnter data filename: ");
      scanf ("%s", filename);
      data = fopen (filename, "r");
      strcpy (name,filename); 
      }
      while (data == NULL);
        while ( fgets (line, LineLength+1, data) != NULL )  /* read each student's data */
         {   
            Curr = &StudentList[CurrNum];
            sscanf (line, "%s %c %f %d %d",Curr->SSN,&(Curr->Class),&(Curr->GPA),&(Curr->Units),&(Curr->NumCourses));
            if ((Curr->NumCourses) == 0)
            (Curr->CourseList = NULL);
            else 
              {
               for(i=0;i<(Curr->NumCourses);i++)
                 {   printf ("In For loop i is:%d Curr->NumCourses is %d\n", i,Curr->NumCourses );
                  New = (Course_T*) malloc ( sizeof (Course_T) ); /* allocate new node space */        
                  if (New == NULL)            
                   printf ("Heap error - could not allocate memory\n");       
                  else 
                    {                               /* Memory allocated successfully */
                    fgets (line, LineLength+1, data); 
                     sscanf (line, "%s %s %d", &New->Number, &New->Section, &(New->Units)); /* Put data into new node */
                     printf ("Number is %s \n Section is %s\n Units are %d\n\n", &New->Number, &New->Section, New->Units);          
                     New->Next = NULL; /* Insert new node into the list */            
                       if (First == NULL) 
                         { /* If list is empty... */              
                         Last = New; /* point both pointers to new node */           
                         First = New;            
                         }             
                       else 
                        { /* If list is not empty... */              
                         Last->Next = New; /* Point Next ptr in last node to new node */               
                         Last = New; /* and also point Last ptr to new node */             
                        }                    
                     } /* end else where New != NULL */      
                  } /* end for */    
                } /* End else *First not null */
            CurrNum++;
         }
     fclose (data);
     return CurrNum;
    }
    /*************************/
    int DisplayStudent (int StudentNum, Student_T* StudentList) /* Display with Num Courses */
    {
       int Num,i;                          /* Loop counter */ 
       char Class1[14] = "Undergraduate";
       char Class2[9] = "Graduate";            
       Student_T* Stud1_ptr;      /* Ptr to student record being displayed */
       Stud1_ptr = StudentList;    /* Ptr to first record in array */
       Course_T*  Course_ptr;
       Course_ptr = First;
       
      printf ("\nSocial Security Number  Classification GPA  Units Number Courses\n");  //Define this as Header
       printf  ("----------------------  -------------- ---  ----- --------------\n");  // use dash = '-' & formatting
       for (Num = 0; Num < StudentNum; Num++) /* Print list of SSNs */
       {     
         if (Stud1_ptr->Class == 'U') // this is ugly try to fix logic
         printf ("%15s  %20s %5.2f %3d %9d\n",Stud1_ptr->SSN,Class1,Stud1_ptr->GPA,Stud1_ptr->Units,Stud1_ptr->NumCourses);
           if (Stud1_ptr->NumCourses > 0)
             for(i=0;i<(Stud1_ptr->NumCourses);i++)
             {    //This needs to point to CourseList Walk the list I guess
    // but how?
              printf ("%s  %s \n", Stud1_ptr->(Course_ptr->Number),Stud1_ptr->(Course_ptr->Section)); //WRONG
            else 
         printf ("%15s  %15s %10.2f %3d %9d\n",Stud1_ptr->SSN,Class2,Stud1_ptr->GPA,Stud1_ptr->Units,Stud1_ptr->NumCourses);
          Stud1_ptr++; /* point to next record */
       }
       printf ("\n");
    }
    Any help would be appreciated. Thank You.

  2. #2
    Registered User
    Join Date
    Jun 2004
    Posts
    277
    I think you can use a function like this:
    Code:
    void printFoo (fooPtr currentPtr){
       if (currentPtr == NULL)
           printf("Foo is empty");
          else {
                printf("Foo is:");
                    while (currentPtr != NULL){
                                printf("%cdf whatever you need", currentPtr->youData);
            currentPtr = currentPtr->nextPtr;
                }
    
    }
    
    }
    the point is that the fooPtr must point to the first element of the list. I dont know if I was clear I'm also kinda new on programming I'm just trying to help

  3. #3
    Registered User
    Join Date
    Nov 2001
    Posts
    38
    I believe you should change your

    Stud1_ptr->(Course_ptr->Number)

    to

    Stud1_ptr->CourseList->Number

    since the Stud structure that is pointed to by Stud1_ptr does not contain an element named Course_ptr.

    EDIT:
    Ah, wait, I see.

    You need to walk through the courses in each student while walking through the students.

    Stud1_ptr is your current student.

    Course_ptr needs to be assigned to the first course of Stud1_ptr every time through your loop since Stud1_ptr changes every time (or it should).
    so Course_ptr = Stud1_ptr->CourseList
    Then you can print info about the course by Course_ptr->Number or whatever.

    Then step to the next course Course_ptr = Course_ptr->next

    Rinse and repeat

    /EDIT:
    Last edited by Rutabega; 02-23-2005 at 02:14 PM.

  4. #4
    Sweet
    Join Date
    Aug 2002
    Location
    Tucson, Arizona
    Posts
    1,807
    Can I make a style suggestion.
    Use more spaces in your code to make it more readable and also a few more spaces after curly braces etc..
    Woop?

  5. #5
    Registered User
    Join Date
    Feb 2005
    Posts
    10
    Thanks for the input, actually, I see now that CourseList is already a pointer to the list.... I'm still confused. But will post what I try and what works or doesn't. This is a test program so the spacing etc is not final.

  6. #6
    Registered User
    Join Date
    Feb 2005
    Posts
    10
    trying to declare a new pointer to work with gives a compiler error:
    Course_T *C_ptr;
    C_ptr = CourseList;

    Trying to decale a pointer on the fly gives a "Start undeclared ":
    Start = &Stud1_ptr->CourseList;

    Trying to use : printf("Number is %s\n", &Stud1_ptr->CourseList.Number);
    gives a " request for member `Number' in something not a structure or union"
    error, as it should I guess. I need to have a pointer to the top of the list, but cant declare one.

  7. #7
    Registered User
    Join Date
    Feb 2005
    Posts
    10
    This does not give an error:
    printf ("Number is %s\n", Stud1_ptr->CourseList->Number);

    Now why does it return null? Continuing...

  8. #8
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    There is not "syntax for printing out the linked list". You simply walk through the list itself, and print each one individually.
    Code:
    struct foo
    {
        ...some data...
        struct bar *list;
    } fooers[ SOMEFOO ];
    
    ...
    int x;
    struct bar *ptr;
    
    /* for each foo */
    for( x = 0; x < SOMEFOO; x++ )
    {
        /* print all of this fooer's data, except the linked list here... */
        printf("all of foo's stuff, except the linked list");
    
        /* now print this fooer's linked list contents... */
        for( ptr = fooers[x].list; ptr; ptr = ptr->next )
            printf("all of the linked list for this fooer gets printed now");
    }
    Naturally, if you've got a pointer to your array instead, you'd use the correct indirection operator.

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

  9. #9
    Registered User
    Join Date
    Feb 2005
    Posts
    10
    That does give a runtime error in VC++, bad pointer....I'm lost again...oh well

  10. #10
    Registered User
    Join Date
    Feb 2005
    Posts
    10
    I'll try your suggestion quzah, thank you

  11. #11
    Registered User
    Join Date
    Feb 2005
    Posts
    10
    With the addition of a pointer on the Course struct:
    Code:
    typedef struct Course {
    char Number [NumSize + 1]; /*Course Number*/
    char Section [SecSize + 1]; /*Course Section*/
    int Units;   /*Course Credits*/
    struct Course *Next; /*Next Course pointer*/
    } Course_T, *Course_ptr; 
    
    typedef struct Stud {           /* Student Records */
        char SSN[SSNsize+1];        /* SS# array of char */
        char Class;                 /* Student Classification */
        float GPA;                  /* Grade Point Average */
        int Units;				/* # of units */
        int NumCourses; /* Number of classes being taken */ 
        Course_T *CourseList; /* Ptr to list of classes */ 
        } Student_T;         /* Struct Type of Student*/
    Student_T StudentList[ListMax];      /* list of student data */
    and trying the folowing:
    Code:
     for( (Course_ptr = Stud1_ptr->CourseList); Course_ptr; (Course_ptr = Course_ptr->next) )
    I get a 'Course_ptr' : illegal use of this type as an expression error.

  12. #12
    Registered User
    Join Date
    Feb 2005
    Posts
    10
    Code:
    Course_ptr = (Stud1_ptr->CourseList);
    This works! Getting closer....

  13. #13
    Registered User
    Join Date
    Feb 2005
    Posts
    10
    I give up, I think I will write any additions to the courseList to a temp file and reread them into memory before I display them. I can't get past the bad ptr error.

  14. #14
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Well you'll never get anyway by giving up. But perhaps it's for the best. However, if you do feel linclined to give it another shot, might I suggest the Linked List Entry Prelude has written in the FAQ?

    If you understand how linked lists work, and you understand how arrays work, then using the code I've provided in my example will have you squared away in no time. It's quite simple if you understand both of those two concepts.

    If not, perhaps as you've suggested, implementing it another way will be best for now.

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

  15. #15
    Registered User
    Join Date
    Feb 2005
    Posts
    10
    I'm not giving up, that was frustration talking...I'll check the FAQ thank you, I think the problem is actually that I'm not capturing the values in the read function. When the function exits the linked list is lost.

    Thank You.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help crating a linked list of array of structs.
    By doubty in forum C Programming
    Replies: 1
    Last Post: 07-05-2009, 08:49 PM
  2. help! Placement of nodes in a Linked List
    By lostmyshadow in forum C Programming
    Replies: 6
    Last Post: 12-17-2007, 12:21 PM
  3. failure to import external C libraries in C++ project
    By nocturna_gr in forum C++ Programming
    Replies: 3
    Last Post: 12-02-2007, 02:49 PM
  4. Replies: 5
    Last Post: 11-04-2006, 05:39 PM
  5. How can I traverse a huffman tree
    By carrja99 in forum C++ Programming
    Replies: 3
    Last Post: 04-28-2003, 05:46 PM

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