Reputation: 1114
I've a trouble about this syntax.
The problem says:
calculate the histogram of occurrences of names using an array of structures allocated dynamically at runtime
I solved it in this way (I preferred to use pastebin to avoid to paste too much code here):
main.cpp http://pastebin.com/TD6Y2Acf
dinalloc.cpp http://pastebin.com/93eM9EdL
dinalloc.h http://pastebin.com/bUX7TxTs
It works, but I cannot understand why...
I declared a struct called hi
and an array of this structures called vet
. When, in the dinalloc.cpp I declare the function parameters, I have to wrote hi *vet
. In this way, it means that I'm saying to the function to expect a pointer to an hi
structure, or not? Instead, when I call the function, I give vet
as parameter, that is an array of hi
structures.
How it's possible that this code works?
P.S. Any advice about my code-writing method is welcome.
Upvotes: 0
Views: 554
Reputation: 1362
Your code is correct. Actually array is a pointer to it's first element, and that's what you've got from your new operator.
Even if you had a code like
const int n = 5;
hi vet[n];
// ...
printHistogram(vet, n);
It is still correct. According to 4.2 paragraph of the c++ standart,
An lvalue or rvalue of type “array of N T” or “array of unknown bound of T” can be converted to a prvalue of type “pointer to T”. The result is a pointer to the first element of the array.
Upvotes: 2