problem on dynamic array
This is the code I saw in mock paper.
What is the difference between class & struct?
int age, strength;
cin >> n;
AntArmy = new Ant[n];//can't get why the structure name can be the array name
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
AntArmy is first declared to be a pointer to the Ant type.
AntArmy = new Ant[n];
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:
Ant* AntArmy = new Ant[n];
Thank you for your clear explanation, I got it.