cppmakesmesad
cppmakesmesad

Reputation: 1

Creating/resizing arrays...can't use non-constant?

I have a struct defined as

struct Point {
int x, int y
}

I am getting an array of Points passed into a function, as well as an integer i that tells me how many elements the array contains. How in the world can I just add an element into the array? I realize there is no method to just add new elements, as arrays can't be dynamically resized, so I need to create a new one and copy each element over...but when I try to do the following:

Point newPoints[i+1];

I am told that it expects a constant value, which of course I can't give it since I need i+1, and i is variable. C++ makes me sad. (If it isn't obvious, I come from a land where some divine being manages all your objects for you...)

P.S. I must use arrays...forgot to mention that.

Upvotes: 0

Views: 362

Answers (3)

Dominik Grabiec
Dominik Grabiec

Reputation: 10665

The reason you must use a constant value is that the newPoints array is being created on the stack, and to do that the compiler must know how big it is going to be at compile time. To be able to specify a dynamic size you must use either new[] and delete[], or a dynamic data structure class (like from the STL).

Upvotes: 0

Jeremiah Willcock
Jeremiah Willcock

Reputation: 30999

In standard C++, you cannot create an array with a run-time-set size. You will need to do one of:

  1. Declare newPoints as a pointer and then allocate the value using new Point[i+1], applying delete [] to it later.
  2. Declare newPoints using something like boost::scoped_array, which manages cleanup automatically.
  3. Use a non-array, such as an std::vector; you can use &v[0] to get a pointer from that.
  4. Use a non-standard extension, such as the one provided by GCC.

Upvotes: 2

J Trana
J Trana

Reputation: 2210

Afraid you're going to have to use a new/malloc on this one. i is only determined at runtime, so there's no way it can statically allocate the memory it needs on the stack at compile time.

Upvotes: 0

Related Questions