0

Elements of array

What if i dont know exactly, how many elements need to be stored in the array? for ex. i want to count vowels in a text, and store them in an array?

21st Nov 2016, 5:23 PM
Benedek Måté Tóth
Benedek Måté Tóth - avatar
2 Answers
+ 1
Why not just use vectors, since you don't know how many elements you need to allocate at compile time (or in this case, even at runtime). If you don't want to use vectors, you could just use dynamic allocation (I mean malloc), allocating more than the size you need. However, you need another variable to track the actual size of the array and free memory after usage. With vectors, things get much easier (though with a slightly higher overhead, not that significant anyway) - vectors automatically grow as you add new items; size() function gives you the actual size of the vector, etc. In short, just use vectors, except if you have a reason why you must use arrays.
21st Nov 2016, 5:54 PM
Rill Chritty
Rill Chritty - avatar
0
oh, thank you, i havent yet learned about vectors, i will look after it!
21st Nov 2016, 6:02 PM
Benedek Måté Tóth
Benedek Måté Tóth - avatar