In: Computer Science
Explain what this code does. Will this work? Let us discuss
cents = new *Ent[num_cents];
for (i=1;i<num_cents+1;i++)
{
cents[i-1] = new Ent();
}
Note: Done accordingly. Please comment for any problem. Please Uprate. Thanks.
This program will not run as new *Ent[num_cents]; is not a valid syntax.
The correct syntax should be :
Ent** cents;
cents = new Ent*[num_cents];
for (i=1;i<num_cents+1;i++)
{
cents[i-1] = new Ent();
}
Here cents will be pointer to pointer to Ent then we will initialize cents as Array of pointers to Ent (Both array and pointer are same). Now in loop we are creating pointer to Ent and saving it array of cents.
Sample Run(With some modifications):
#include<iostream>
using namespace std;
class Ent{
public:
int a;
Ent(int a){
this->a=a;
}
};
void main(){
const int num_cents=5;
int i;
Ent** cents;
cents = new Ent*[num_cents];
for (i=1;i<num_cents+1;i++)
{
cents[i-1] = new Ent(i);
}
for (i=1;i<num_cents+1;i++)
{
cout<<cents[i-1]->a<<endl;
}
}