How to get size c++ dynamic array

"How to get size of dynamic array in functions? Because it seems the passing size of array n in every function is the wrong way."

Yet it is the only way when you use dynamically allocated C-style array.

If you want to avoid sending the size explicitly then pass some object that wraps this raw memory buffer and provides other means of retrieving the size. The most reasonable solution here would be using std::vector<Airplane>.


1) Ommiting the irrelevant, this is basically what you got:

cin >> n;
getline(cin, type);

operator>> leaves a new-line character in the input buffer and that's the first character that getline sees. Since '\n' is the default line delimiter, you get an empty line. To fix it call cin.ignore() before you call getline to discard the '\n'.

2) If you wish to stick with raw pointers, passing the size as a parameter is your only choice. Switch to std::vector and you get size() method that you can query at any time.


The problem with entering type is that the input buffer contains the new line character after entering n. You should use member function ignore to clear the buffer before using function getline.

As for your second question then in general you should track the size of a dynamically allocated array yourself. Or you can set the last element of the array as NULL and use it as a sentinel.