Thread: structurs

  1. #1
    Registered User
    Join Date
    Dec 2009
    Posts
    1

    structurs

    Hello,
    I am tring to add new structure to slist.
    I am not sure this is the right way to do it.
    I have a broblem when i'm tring to put the fildes id and name (run time eror).

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    typedef struct student {
    	char *name;
    	int id;
    	struct clist *courses;
    } student;
    
    typedef struct course {
    	char *title;
    	int number;
    	struct slist *students;
    } course;
    
    typedef struct slist {
    	student *info;
    	struct slist *next;
    } slist;
    
    typedef struct clist {
    	course *info;
    	struct clist *next;
    } clist;
    
    //prototypes
    slist* add_student(slist *students, char *name, int id);
    
    
    //main function - only to check the program
    void main(){
    	char *name[256];
    	int id;
    	slist *students = NULL;
    
    	printf("Enter your name\n");
    		scanf("%s",&name);
    		printf("Enter your id\n");
    		scanf("%d",&id);
    		add_student(students,name,id);
    }
    
    //Basic Operations
    slist* add_student(slist *students, char *name, int id){
    
    	slist *head = (slist*) malloc(sizeof(slist));
    	
    	strcpy(head->info->name, students->info->name);
    	head->info->id = id;
    	if (!head ) return NULL;
    	head->next = students;
    
    	return head;
    	}

  2. #2
    Registered User
    Join Date
    Oct 2006
    Location
    Canada
    Posts
    1,243
    In main, you declare "students" and assign it "NULL". Then, in "add_student", you try to access a field of it ("->info"), which will give you a segfault. You need to allocate memory for "students" before using it.

  3. #3
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    To expand upon that point:
    Code:
    slist* add_student(slist *students, char *name, int id){
    
    	slist *head = (slist*) malloc(sizeof(slist));
    	
    	strcpy(head->info->name, students->info->name);
    	head->info->id = id;
    	if (!head ) return NULL;
    	head->next = students;
    
    	return head;
    	}
    Here again, you start fiddling with the memory, and afterwards you check to see if it's OK to do so. You should make sure it's valid before you start using it, not after.


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

Popular pages Recent additions subscribe to a feed