How can I fix the error & ldquo; An object of variable size may not be initialized?

advertisements

How can I fix the error "Variable-sized object may not be initialized" with the following code:

sv A[i] =new sv(m,t,d,l,tl,ml,nh);

My code from the beginning to the error line:

#include<iostream>
#include<conio.h>
#include<string>
using namespace std;

class sv{
public: int msv;
  string ten,lop;
  float diem;
  string tenlop, malop;
  int namhoc;
  sv();
  sv(int m,string t, float d,string l,string tl,string ml, int nh);
class lophoc{
public:
  lophoc();
  lophoc(string tl,string ml, int nh); };
  void hienthi(){
  cout<<msv<<"\t"<<ten<<"\t"<<diem<<"\t"<<tenlop<<"\t"<<malop<<"\t"<<namhoc<<"\n";
            }
 };
  sv::sv(){ }
  sv::sv(int m,string t, float d,string l,string tl,string ml, int nh)
  {
    msv=m; ten=t; diem=d; lop=l; tenlop=tl; malop=ml, namhoc=nh; }
int main(){
  sv A[100];
  int n,i,m,d,nh;
  string t,tl,ml,l;
  cin>>n;
  for(i=1;i<=n;i++){
  cout<<"lan luot nhap ma sv,ten, diem,lop hoc: ";
  cin>> m>>t>>d>>l;
  cout<< "lan luot nhap ten lop, ma lop, nam hoc: ";
  cin>>tl>>ml>>nh;
  sv A[i] =new sv(m,t,d,l,tl,ml,nh);
}
}


This:

sv A[i] =new sv(m,t,d,l,tl,ml,nh);

looks like a declaration of another array of sv called A with run-time size of i to the compiler (A C99 feature). If you wanted to assign to the element at index i, you would do:

A[i] = sv(m,t,d,l,tl,ml,nh);

Note that new allocates on the heap and returns a pointer, which is not required here.