10

they say "you can do anything on C++"

I can't even initialize an array with a random length

Comments
  • 7
    #include <ctime>
    #include <vector>
    int main()
    {
    std::srand( std::time(NULL) );
    std::vector<char> arr( std::rand() );
    return 0;
    }

    could work. srand sets the seed for the rand random number generator to the result of time(NULL), which returns the milliseconds from some time in 1970 - eg changes every milisecond - and vector is a class for dynamic arrays. a vector allocates a memory range on the heap(RAM) and stores a pointer to it. you could just aswell allocate an array at runtime yourself using

    char* arr = new char[rand()];

    which leaves you with a pointer to the beginning of an array which is sizeof(char)*rand() bytes long.

    hopefully this helped
  • 3
    @simulate wtf your likes are binar ...
  • 0
    @Draedus
    yours too 😶 😃
  • 0
    I mean std::array
  • 2
    @simulate :)) I thought i'm too drunk but is real :)))
  • 3
    You can use this compile time random number generator: https://youtu.be/rpn_5Mrrxf8 which returns constexpr number which can be used to initialize the size of an array
  • 2
    @funvengeance
    std::array holds a static array, declared like

    Type name[const_size];

    In C++ you are often concerned with performance and optimization and therefore the to-go approach for arrays are fixed size arrays. Resizable arrays must always be ready to change their size, which means you may have to copy the entire array to another place in memory which is guaranteed to be large enough to hold the new size.
  • 2
    Don't you have malloc
  • 3
    @Teknas malloc is used in C, in C++ there is 'new'. And there is e.g. std::vector which uses dynamic allocation, but he wants to use std::array which needs to know its size at compile time
  • 1
    int[] myRandomLengthArray = {1, 2, 3, 4};

    (Four was chosen randomly by a fair dice roll)
  • 0
    one way is @binary 's way. But I wadted so much time, thought it is my fault
  • 0
    @funvengeance
    Why do you need the array size to be known at compile time?
  • 0
    I need the size to put it in the std::array template
Add Comment