Thread: Problem with Linked List

  1. #1
    Registered User
    Join Date
    Jan 2014
    Posts
    10

    Problem with Linked List

    Hi guys! I've been having problem with my code below:

    Code:
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    
    typedef struct students{
        char studentName[3];
        struct students *next;
    }student;
        
    typedef struct courses{
        char courseCode[3];
        student *studentPtr;
        struct courses *next;
    }course;
    
    
    main(){
        int choice, numCourse, i=0, j, c, d;
        char fileName[100], courseLists[numCourse][9999], temp[9999];
        course *head = NULL, *ptr;
        student *headStud, *newStud;
    
    
            printf("Enter number of courses: ");
            scanf("%d", &numCourse);
    
    
            printf("Enter course name followed student names: \n");
            for(i=0;i<numCourse;i++){
                scanf(" %[^\n]", temp);
                strcpy(courseLists[i], temp);
                j = 0;
                course *newCourse = (course *)malloc(sizeof(course));
                while(courseLists[i][j]!=' '){
                    newCourse->courseCode[j] = courseLists[i][j];
                    j++;
                }
                if(head==NULL){
                    head = newCourse;
                    ptr = newCourse;
                }else{
                    while(head->next!=NULL) head = head->next;
                    head->next = newCourse;
                }
            
                headStud = NULL;
                if(headStud==NULL){
                    newStud = (student *)malloc(sizeof(student));
                    headStud = newStud;
                    newCourse->studentPtr = newStud;
                }
                
                for(d=4;d<strlen(courseLists[i]);d++){
                        newStud->studentName[c] = courseLists[i][d];
                        c++;
                    if(c==3){
                        newStud = (student *)malloc(sizeof(student));
                        c = 0;
                        while(headStud->next!=NULL) headStud = headStud->next;
                        headStud->next = newStud;
                        d++;
                    }
                }
            }
    
    
            while(ptr!=NULL){
                printf("%s ", ptr->courseCode);
                while(ptr->studentPtr!=NULL){
                    printf("%s ", ptr->studentPtr->studentName);
                    ptr->studentPtr = ptr->studentPtr->next;
                }
                printf("\n");
                ptr = ptr->next;
            }
    }
    The input goes like this:
    c01 jjd kks jjd
    c02 jdj mms dds

    Yes. This is actually an Exam Scheduling Problem where c01 is the course name, jjd, kks, etc. are the initials of the students.

    course names are stored in courseCode element of the course linked list, while student names are stored in studentName element of the student linked list.

    Sometimes the code works, sometimes it says segmentation fault (core dumped)

    Help please!

  2. #2
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    Code:
     courseLists[numCourse][9999]
    This declaration isn't going to work. You have to declare this after numCourse has a value. The ability to define arrays with a variable length is a C99 feature, though.

  3. #3
    Registered User
    Join Date
    Dec 2011
    Location
    Namib desert
    Posts
    94
    In main() you make the following declaration: courseLists[numCourse][9999]

    At that point, the value of numCourse is undefined !

  4. #4
    Registered User
    Join Date
    Dec 2011
    Location
    Namib desert
    Posts
    94
    After using malloc() in order to allocate a new struct, it is saver to directly let the struct's next pointer point to NULL

  5. #5
    Registered User
    Join Date
    Jan 2014
    Posts
    10
    Thank you so much guys! I've figured it out a while ago and the problem was indeed the courseLists. )

  6. #6
    Registered User
    Join Date
    Jan 2014
    Posts
    10
    BTW, do you guys have any idea on how I to get an array of string input without declaring its size?
    For instance, I use temp in the above code but the size is specified. Is there any way? Thank you!

  7. #7
    Registered User
    Join Date
    Dec 2011
    Location
    Namib desert
    Posts
    94
    Although I did not test it, I would use something like:

    char **strAr;
    int arSize;

    char someTempString[256];
    int lengthOfSomeTempString;

    .......
    // arSize gets some value ....
    strAr = malloc(arSize * sizeof(char **));

    // input value into someTempString for example through scanf()

    strAr[0] = malloc(lengthOfSomeTempString + 1);
    strcpy(strAr[0], someTempString);

  8. #8
    Registered User
    Join Date
    Dec 2011
    Location
    Namib desert
    Posts
    94
    btw, one should always test for malloc's return value (shouldn't be null)

  9. #9
    Registered User
    Join Date
    Jan 2014
    Posts
    10
    Quote Originally Posted by ddutch View Post
    btw, one should always test for malloc's return value (shouldn't be null)
    Yes, yes. Thank you so much!

  10. #10
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    Quote Originally Posted by ddutch View Post
    Although I did not test it, I would use something like:
    That code offers nothing much better than what was used though.

    Normally if you don't have exact limits on the size of a string or something, you're forced to resize the string repeatedly.

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int main() {
    	char *line = NULL;
    	char *pos;
    	char *nl;
    	
    	const int BufferSize = 20;
    	int length = BufferSize;
    	if ((line = malloc(length)) != NULL) {
    		puts("enter something: ");
    		fgets(line, BufferSize, stdin);
    		
    		while ((nl = strchr(line, '\n')) == NULL) {
    			char *temp;
    			length += BufferSize;
    			if ((temp = realloc(line, length)) == NULL) {
    				free(line);
    				puts("memory exhausted... dying");
    				return -1;
    			}
    			pos = line = temp;
    			pos += strlen(line);
    			fgets(pos, BufferSize, stdin);
    		}
    		*nl = '\0';
    		
    		puts(line);
    		free(line);
    	}
    	return 0;
    }
    
    #if 0
    my output
    
    C:\Users\Josh2\Documents>lines
    enter something:
    This is a very long sentence unlikely to be covered in one go by the code
    This is a very long sentence unlikely to be covered in one go by the code
    
    C:\Users\Josh2\Documents>lines
    enter something:
    This is an even longer sentence that does not get the benefit of being complete
    ly read in one go by the code.
    This is an even longer sentence that does not get the benefit of being complete
    ly read in one go by the code.
    #endif
    I used a small buffer size on purpose, but you could easily use BUFSIZ instead.

  11. #11
    Registered User
    Join Date
    Jan 2014
    Posts
    10
    Quote Originally Posted by whiteflags View Post
    That code offers nothing much better than what was used though.Normally if you don't have exact limits on the size of a string or something, you're forced to resize the string repeatedly.
    Code:
    #include #include #include int main() {	char *line = NULL;	char *pos;	char *nl;		const int BufferSize = 20;	int length = BufferSize;	if ((line = malloc(length)) != NULL) {		puts("enter something: ");		fgets(line, BufferSize, stdin);				while ((nl = strchr(line, '\n')) == NULL) {			char *temp;			length += BufferSize;			if ((temp = realloc(line, length)) == NULL) {				free(line);				puts("memory exhausted... dying");				return -1;			}			pos = line = temp;			pos += strlen(line);			fgets(pos, BufferSize, stdin);		}		*nl = '\0';				puts(line);		free(line);	}	return 0;}#if 0my outputC:\Users\Josh2\Documents>linesenter something:This is a very long sentence unlikely to be covered in one go by the codeThis is a very long sentence unlikely to be covered in one go by the codeC:\Users\Josh2\Documents>linesenter something:This is an even longer sentence that does not get the benefit of being completely read in one go by the code.This is an even longer sentence that does not get the benefit of being completely read in one go by the code.#endif
    I used a small buffer size on purpose, but you could easily use BUFSIZ instead.
    Thank you so much! :*

  12. #12
    Registered User
    Join Date
    Dec 2011
    Location
    Namib desert
    Posts
    94
    That code offers nothing much better than what was used though.
    The question was:
    BTW, do you guys have any idea on how I to get an array of string input without declaring its size?
    the answer is a char **

    I also think that it's more efficient to use an oversized input-buffer for the strings instead of realloc-ing all the time. Additionally one can put a safe limit on the maximum length of the user-input.

  13. #13
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    the answer is a char **
    I think, together, our suggestions will work to create an array of any size that contains string elements of any size. Your answer was incomplete, because it assumed specific sizes, and you didn't demonstrate realloc() at all. The whole point of dynamic memory is that it is flexible. With my demonstration of calling realloc(), all that the OP has to do now is call realloc() when she runs out of preallocated char* in the array which works the same when you call it to resize anything else.

    I also think that it's more efficient to use an oversized input-buffer for the strings instead of realloc-ing all the time.
    It is, since not calling realloc() is always going to be more efficient than actually calling it. However, realloc() has a purpose in creating flexible arrays, so I don't see a point in arguing. With a big magic number like BUFSIZ, reallocation can be made infrequent and the effects of its drawbacks, such as memory fragmentation, can be minimized to the point that you won't see any performance hit most of the time.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem on Linked list
    By shyam09 in forum C Programming
    Replies: 29
    Last Post: 07-23-2013, 12:25 AM
  2. Linked List Problem
    By toonlover in forum C++ Programming
    Replies: 1
    Last Post: 07-12-2008, 03:54 AM
  3. linked list problem~~~
    By nishu1988 in forum C Programming
    Replies: 2
    Last Post: 07-22-2007, 03:54 AM
  4. Replies: 6
    Last Post: 03-02-2005, 02:45 AM
  5. syntax linked list problem & struct problem
    By beely in forum C Programming
    Replies: 5
    Last Post: 11-11-2002, 09:14 AM

Tags for this Thread