my list error!!

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • wbgxx
    New Member
    • Jan 2010
    • 6

    my list error!!

    Code:
    #include<iostream>
    using namespace std;
    class list
    {
    public:
    	int number,score;
    	char name[10];
    	class list*next;
    };
    
    void create(list* head)
    {
    	list* p=head;
        while(1)
    	{
    		list* pp=new node;
    		if(!pp)
    		{
    			cout<<"erroe"<<endl;
    			exit(1);
    		}
    		cout<<"Please input the student ID:";
    		cin>>pp->number;
    		if(pp->number==0)
    			break;
    		else
    		{
    			
    			cout<<"Pleast input the studnet name";
    			cin>>pp->name;
    			cout<<"Please input score:";
    			cin>>pp->score;
    			p->next=pp;
    			p=pp;
    		}
    		
    	}
    }
    
    void show(list* head)
    {
    	list* ptr=head;
    	cout<<"\n --  STUDNET  ---"<<endl;
    	cout<<"ID\tNAME\tscore\n============================"<<endl;
    	while(ptr!=NULL)
    	{
    		cout<<ptr->number<<"\t"<<ptr->name<<"\t"<<ptr->score<<endl;
    		ptr=ptr->next;
    		
    	}
    }
    		
    int main()
    {
    	list* head=NULL;
    	create(head);
    	show(head);
    	return 0;
    }
  • wbgxx
    New Member
    • Jan 2010
    • 6

    #2
    there is a error in runtime

    Comment

    • weaknessforcats
      Recognized Expert Expert
      • Mar 2007
      • 9214

      #3
      It looks like head in NULL in main() after the return from create. Then you use the null pointer with the -> operator in show and die right there.

      You need to pass the address of head to create. The argument to create should be list** so you can put the address of the created node into head by using *head = new node in create.

      Do you have a debugger you can use? Usually you can step through code and see exactly where it fails.

      Comment

      • johny10151981
        Top Contributor
        • Jan 2010
        • 1059

        #4
        In line 56 you have called create function with variable head which is null

        In line 13 you have assigned
        p = head
        which mean p is null;
        but in line 33 you did
        p->next=pp;
        but still p is null. You cant do that. Try allocate some memory.

        But you should also check your logic. Cause in line 34 you did
        p=pp;

        So re-think what do want to do...
        I think your logic will be something like that... First before line 56 allocate some memory for head(use malloc).

        in the function do something like that (or better you think)
        while()
        {
        ...
        some logic to control loop.
        ...
        pp = new ...();
        p->next=pp;
        p->...=your_data( );
        }while()

        above logic is not complete. You better complete yourself. (I am not that good)

        Best Regards,
        JOHNY

        Comment

        Working...