Fix off would like to point out that your code is leaking memory. It is very important to remember that
whenever you do call
new
you NEED to have a matching
delete
call.
So at the end of int main() you should have this
delete[] Sarr;
.
Now the first problem you have is that in your student struct you declared a constructor which means that there is no longer a implicitly generated default constructor. So since we don't have a default constructor when we try to do
new student[10];
it will fail because it is trying to call a default constructor which isn't there.
To fix this you need to define a default constructor for the student struct which assigns whatever values you think are good for the members in your struct.
For example
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
struct student{
char name;
int age;
char stream;
int mark;
// When you declared this it deleted the default constructor
// that the compiler generates for you.
student( char n, int a, char s, int m);
// Default constructor
student() : name(' '), age(0), stream(' '), mark(0) {}
};
|
Now on to your next problem. The problem is that you are treating the Sarr pointer as a actually array variable. It is not a array. It is a pointer to a student object within that array.
When you do
1 2
|
student *Sarr;
Sarr = new student[10];
|
the variable Sarr is pointing to the first element in a array full of 10 student objects.
So when you get into your for loop and try calling
student Sarr[i] = student(n,a,s,m);
you have multiple problems.
1. -
student Sarr[i]
is not valid code. You are telling the compiler that you wish to declare a new variable of type student but it is illegal to have [i].
To fix this get rid of the
(You need to get rid of the [i] also but I will cover that in a sec) so it looks like
Sarr[i] = student(n,a,s,m);
.
2. - Now that it looks like
Sarr[i] = student(n,a,s,m);
we need to do something else. Since Sarr is a pointer we can have random access so we need to get rid of the [i] so it looks like
Sarr = student(n,a,s,m);
. We also need to do one more thing to this statement. Since you declared the array dynamically you need to dynamically declare the object you wish to put in the array. So we need to do this instead
Sarr = new student(n,a,s,m);
.
3. - Now that we got rid of the random access we need to increment that pointer to the next element in the array. So right after
Sarr = student(n,a,s,m);
we need to do this.
1 2
|
Sarr = student(n,a,s,m);
++Sarr;
|
Now I was just going off your current code so I should point out there is much easier ways to do this like not dynamically declaring the array and other things. So you might want to explore those options also. Hope this is of some help.