Hello everyone, I am doing a textbook question, I dynamically allocated object pointer and want to pass input value into "* Tests",but the program stopped working after I run into the for loop. any help will be appreciated Thank you!!
#include<iostream>
#include<string>
#include <stdio.h>
#include <string.h>
#include <iomanip>
#include <cstdlib>
#include <cctype>
usingnamespace std;
struct Course
{
string Name;
int IdNumber;
int *Tests;
int Average;
int courseGrade;
};
void Result(int,int );
int main()
{
cout<<"please enter number of test score ";
int testScore;
cin>>testScore;
int numberofStudents;
cout<<"please enter number of student there is ";
cin>>numberofStudents;
Result(numberofStudents,testScore);
}
void Result(int numberofStudents,int testScore)
{
constint Size=numberofStudents;
constint Size1=testScore;
Course *object=nullptr;
object=new Course[testScore];
for(int i=0;i<testScore;i++)
{
cin>>*object[i].Tests;
}
}
for(int i=0;i<=testScore;i++) //out of bounds. it should be i<testScore
{
cin>>*object[i].Tests; //Test is a null pointer. You cannot dereference null pointers
}
Line 38: You're allocating an array of Courses with testScore occurrances.
This doesn't make sense. Why does testScore control how many Course instances you allocate?
After line 38, you need to allocate Tests
1 2
object->Tests = newint[testScore]; // Assuming testScore is the number of tests you want to allocate. per Course.
You really should be doing this in a constructor for COurse.
Don't forget to delete Tests[].
Line 41: Tests is an array, you will need an additional loop to iterate through the Tests.
Line 41: You don't initialize the values of the Tests array. You're going to be printing garbage.
Line 43: You have a memory leak. You don't delete object[].
Thank you I am doing a text book question, it specifically asked that "how many score there are and how many student there are it should then dynamically allocate an array of structures, each structure's Test member should point to a dynamically allocated array that will hold the test scores,after array has been dynamically allocated the program should ask for the id number and test score for each student".
I haven't really learned constructor at this stage, is there a way to allocate test without constructor.
how many score there are and how many student there are
I think you missed my point. I'm presuming here that your Course object represents a student. At line 38, you're allocating an array of Courses (students) based on the number of test scores. You should be allocating the Course array based on the number of students.
object=new Course[numberofStudents];
is there a way to allocate test without constructor.
Yes. I gave that to you in my previous post.
object->Tests = newint[testScore];
BTW, your variable naming could use come improvement.
testscore - This sounds like a score on a test, not the number of scores per Course.
Course - If this represents a student, while not call it Student?