Reputation: 1
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
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
Reputation: 30999
In standard C++, you cannot create an array with a run-time-set size. You will need to do one of:
newPoints
as a pointer and then allocate the value using new Point[i+1]
, applying delete []
to it later.newPoints
using something like boost::scoped_array
, which manages cleanup automatically.std::vector
; you can use &v[0]
to get a pointer from that.Upvotes: 2
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