Dynamic Array Size in C++ -


i looking way dynamically set size of integer array depending on passed parameter. example in pseudocode:

int myfunction(int number) {   int myarr[amount of digits in number]; } 

so when input 13456 int array[] size should 5. whats quickest way in c++, when don't know constant size?

you cannot create array run-time size, must known @ compile time. recommend std::vector instead.

one solution count characters after converting string

#include <string> int myfunction(int number) {     std::vector<int> myarr(std::to_string(number).size()); } 

mathematically, can take log (base 10) find number of digits in number.

#include <cmath> int myfunction(int number) {     int numdigits = static_cast<int>(std::log10(number)) + 1;     std::vector<int> myarr(numdigits); } 

Comments

Popular posts from this blog

python - TypeError: start must be a integer -

c# - DevExpress RepositoryItemComboBox BackColor property ignored -

django - Creating multiple model instances in DRF3 -