Howdy_McGee
Howdy_McGee

Reputation: 10673

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++?

Upvotes: 0

Views: 135

Answers (2)

cnicutar
cnicutar

Reputation: 182774

The problem is there's no memory associated with ordered. You have some options:

  • Assign some memory to ordered using new[]
  • Use a std::vector<int> instead

If you use the vector you can allocate memory right at the beginning or use its push_back method which will cause it to grow as needed.

Upvotes: 4

Alok Save
Alok Save

Reputation: 206646

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.

Upvotes: 5

Related Questions