Dynamic Array in Stack

Why doesn't C++ support dynamic arrays on the stack?

I think, it's because C++ provides superior solutions: std::vector<T> and std::array<T,N> (C++11); though the latter is not dynamic as such but it's superior to raw arrays. You can always know the size, no matter which function you pass the vector or array.

Since C cannot provide these solutions, C99 came up with Variable Length Array (VLA). It has the same problem as regular arrays: it decays into a pointer on passing it to function, and you no longer know the size of the array.

And as Florian Weimer asked here at comp.std.c++ that if C++0x allows VLA, then what would the following code mean?

int vla[n]; //n is known at runtime!
std::vector<decltype(vla)> v; //what does this mean?

How is the compiler going to instantiate the vector template at compile-time when it's type argument depends on n which is known at runtime?

Trying to add an element to a dynamic array

Your loop is exceeding the bounds of the old array if it is not empty. And your assignment of the newCustomer is exceeding the bounds of the new array.

Try this instead:

void Bank::addCustomer(const Customer& newCustomer) {

int count = getCustomerCount();
Customer* temp = new Customer[count + 1];

for (int i = 0; i < count; ++i) {
temp[i] = customers[i];
}
temp[count] = newCustomer;

delete[] customers;
customers = temp;

++customerCount;

//log
}

Dynamic Array implementation in C++

In your resize method you copied over the existing elements from arr

for (int i = 0; i < size; i++) { temp[i] = arr[i]; }

But then later you 0 all of the elements out, effectively clearing the previous data

for (int i = 0; i < capacity; i++) { arr[i] = 0; }

Instead you likely just want to 0 the trailing new elements

for (int i = size; i < capacity; ++i) { arr[i] = 0; }


Related Topics



Leave a reply



Submit