0

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.

nsanders
  • 12,250
  • 2
  • 40
  • 47
Overflowh
  • 1,103
  • 6
  • 18
  • 40

1 Answers1

2

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.

prazuber
  • 1,352
  • 10
  • 26
  • @PraZuBeR So, it's not important that hi is a structure? It's enough that I declare the pointer to hi and then give tu the function (when i call) a pointer to an array? Or it's the array that is a generic pointer to a memory area? – Overflowh Dec 13 '11 at 21:48
  • 1
    @unNaturhal It is important that hi is the type that function expects. But it's not important how hi was declared: new hi; or new hi[n]; the function will work correctly in both cases, just don't forget in the first case to set n to one when you'll be passing it to the function. – prazuber Dec 14 '11 at 14:14
  • @PraZuBeR Mmmh, but hi is the type expected by the function. What I pass to the function is vet. Writing hi *vey = new hi[n]; I'm declaring vet as a pointer to the hi type, or not? – Overflowh Dec 14 '11 at 22:29
  • 1
    @unNaturhal Yes. In this case, vey is a pointer to the first hi structure in a row. vey is pointing to the first hi structure, vey+1 is pointing to the second hi structure, ... , vey+n-1 is pointing to the last hi structure. – prazuber Dec 14 '11 at 23:00
  • @PraZuBeR Aaaah! Understood! Thank you very much for your explanation! :) P.S. Could you link me the C++ standard where did you get the 4.2 paragraph? – Overflowh Dec 14 '11 at 23:19
  • 1
    @unNaturhal Sure. [C++ Standart (draft 3242)](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2011/n3242.pdf) – prazuber Dec 14 '11 at 23:22