-
problem on dynamic array
This is the code I saw in mock paper.
Code:
struct Ant
{
int age, strength;
};
int n;
cin >> n;
Ant *AntArmy;
AntArmy = new Ant[n];//can't get why the structure name can be the array name
AntArmy[0].age=1;
AntArmy[0].strength=5;
What is the difference between class & struct?
Why is the structure name used as the array name?
What 's going on with AntArmy = new Ant[n];?
Thanks in advance!
-
The difference between class and struct is that everything in a class is private by default, but everything in a struct is public by default. Other than that a C++ class and a C++ struct are identical.
The structure name is not used as an array name. The line "AntArmy = new Ant[n];" is an instruction to dynamically allocate and construct and array of n Ant's, and then give AntArmy a value which is the address of the first element in that dynamically allocated array.
-
To add to what grumpy said, pay attention to these two lines
Code:
Ant *AntArmy;
AntArmy = new Ant[n];
AntArmy is first declared to be a pointer to the Ant type.
Then AntArmy is assigned the the first element of a dynamically allocated array of Ant types.
The expression new Ant[n] allocates an array of Ant types and returns a pointer to the first element
AntArmy is assigned that pointer.
That would have been the same as simply writing:
Code:
Ant* AntArmy = new Ant[n];
-
Thank you for your clear explanation, I got it.