Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    Regular Coder
    Join Date
    Nov 2002
    Posts
    180
    Thanks
    0
    Thanked 0 Times in 0 Posts

    null pointer assignment

    when i run this program it run correctly but in the end it tells me "null pointer assinmebt" what does it mean?
    Code:
    #include <iostream.h>
    
    struct student { 
    	char *name; 
    	float grade; 
    };
    
    void main() {
    	student *s;
    	float sum=0;
    	float class_grade;
    	int n;
    	cout <<"Enter students number (less or equal 10): ";
    	cin >> n;
    	s = new student[n];
    
    	for(int i=0; i<n; i++) {
    		cout <<"\nEnter student's name: ";
    		cin >> s[i].name;
    		cout <<"\nEnter student's grade: ";
    		cin >> s[i].grade;
    		sum = sum + s[i].grade;
    	}
    	class_grade = sum / n;
    	cout <<"\nThe class grade is: "<<class_grade;
    
    	cout <<"\nThe students with grade less than the class grade are: ";
    	for(i=0; i<n; i++) {
    		if(s[i].grade<class_grade)
    			cout <<s[i].name<<"\n";
    	}
    
    	cout <<"The students with grade more than the class grade are:\n ";
    	for(i=0; i<n; i++) {
    		if(s[i].grade>=class_grade)
    			cout <<s[i].name<<"\n";
    	}
    }

  • #2
    Senior Coder Mhtml's Avatar
    Join Date
    Jun 2002
    Location
    Sydney, Australia
    Posts
    3,531
    Thanks
    0
    Thanked 1 Time in 1 Post
    It means you're assigning a value through a pointer that points to nothing ie -- a NULL pointer.
    Omnis mico antequam dominus Spookster!

  • #3
    Regular Coder
    Join Date
    Feb 2004
    Location
    WA
    Posts
    213
    Thanks
    0
    Thanked 0 Times in 0 Posts
    You defined student.name as a pointer
    Code:
    struct student { 
    	char *name; 
    	float grade; 
    };
    and you are trying to read a string into it without allocating memory!
    Code:
    	for(int i=0; i<n; i++) {
    		cout <<"\nEnter student's name: ";
    		cin >> s[i].name;
    You have allocated memory to the student structure itself. not the name member of it. The result of this would vary a lot from crash right at the start to perfect function of it if you get lucky.
    Nobody is Perfect. I am Nobody.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •