Search code examples
c++arraysdynamicintegerdynamic-arrays

Trouble Creating Dynamic Integer Array


I'm sure it's something small but I keep getting an initialize error about how I keep trying to use it before it's initialized.

#include <iostream>
using namespace std;
int main()
{
    int* ordered;

    ordered[0] = 5;
    cout << ordered[0];
    return 0;
}

Bonus question, can I use *ordered to access the beginning address and loop through the array using *ordered++?


Solution

  • int* ordered;
    ordered[0] = 5;
    

    ordered is an uninitialized pointer. It points to any random address. Dereferncing such a pointer results in Undefined behavior and will most likely crash your program.
    To be able to do something meaningful with this pointer it needs to point to some valid memory region. You can do so with:

    int *ordered = new[x];
    

    Now, ordered points to a memory region big enough to hold x integers. But, you have to remember to deallocate the memory after usage:

    delete []ordered;       
    

    In C++, you are much better off using std::vector instead of a dynamically allocated array because you do not have to the manual memory management that comes with using new []. Simply said, it is difficult to go wrong with std::vector.