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
Sorting Two Corresponding Arrays
How to Check Whether Two Matrices Are Identical in Opencv
Is Std::String Ref-Counted in Gcc 4.X/C++11
What Does {0} Mean When Initializing an Object
How Does the Range-Based for Work for Plain Arrays
How to Generate a Random Double Uniformly Distributed Between 0 and 1 from C++
Compiling a Static Executable with Cmake
Tell Gdb to Skip Standard Files
Escaping a # Symbol in a #Define MACro
How to Get a List of Video Capture Devices (Web Cameras) on Linux ( Ubuntu )? (C/C++)
Cout or Printf Which of the Two Has a Faster Execution Speed C++
Using Struct Keyword in Variable Declaration in C++
Why Is This Code Trying to Call the Copy Constructor
Is Std::Vector Copying the Objects with a Push_Back
Is There a Linq Library for C++
How to Sort a Std::Map First by Value, Then by Key
How to Strip All Non Alphanumeric Characters from a String in C++