简体   繁体   中英

Dynamic Array Size in C++

I am looking for a way to dynamically set the size of an integer array depending on the passed parameter. For example this in pseudocode:

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

So when the input is 13456 then the int array[] size should be 5. Whats the quickest way to do this in C++, when I don't know the constant for the size?

You cannot create an array with run-time size, it must be known at compile time. I would recommend a std::vector instead.

One solution would be to count the characters after converting to a string

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

Mathematically, you can take the log (base 10) to find the number of digits in a number.

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

An additional option you could do is to avoid using an array altogether by accessing the digits of the number directly:

unsigned int getDigit(unsigned int number, unsigned int index) {
  // See http://stackoverflow.com/questions/4410629/finding-a-specific-digit-of-a-number
}

unsigned int setDigit(unsigned int number, unsigned int index, unsigned int newVal) {
  // intPower is from the question linked to above.
  return number - get(number, index)*intPower(10, index) + newVal*intPower(10, index);
}

unsigned int size(unsigned int number) {
  // See http://stackoverflow.com/questions/1306727/way-to-get-number-of-digits-in-an-int
}

unsigned int push_back(unsigned int number, unsigned int newDigit) {
  // Assuming no overflow
  return 10*number + newDigit;
}

unsigned int pop(unsigned int number) {
  // Assume number != 0
  return number / 10;
}

This lets you treat your number as an array without actually initializing the array. You can even turn this into a class and use operator overloading to get actual array semantics.

You may use vector instead - actually I think the best option in this case. Create a vector with some initial size. Then you may dynamically increase it -

int initialSize = 5;                    
vector<int> myvector(initialSize, 0);   //hold "initialSize" int's
                                       // and all initialized to zero
myvector[0] = 567;                   // assign values like a c++ array

With my gcc version 4.6.3 the following is possible:

int MyFunction(int number)
{
    int myarr[int(ceil(log(number)))];

    ....

    return 0;
}

Edit: C99 this is valid see: Array size at run time without dynamic allocation is allowed?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM