Reputation: 20624
If I have this float array declaration:
float tables[10];
How can I change the length of the 'tables' array to 20?
Another question related to the array in C++:
I can not declare an array something like this:
int length=10;
float newTables[length]; // error C2133: 'newTables' : unknown size
Thanks in advance.
Upvotes: 3
Views: 352
Reputation: 1199
If you are fine defining the size of array during build-time, you can use #define
#DEFINE ARRAY_SIZE 20
float tables[ARRAY_SIZE];
Or if you need to specify the size of array during runtime, use new
float* newtables;
newtables = new float[20];
Upvotes: 1
Reputation: 1
You can not change the length of an array dinamically while running program in C++. About the way you want to declare the array I suggest you the following:
const int length=10;
float newTables[length];
I'm not sure if it's what you want. In this case the variable "length" is a constant and can not be changed in execution.
I hope it helps you.
Upvotes: 0
Reputation: 59811
Arrays in C++ have a fixed length. If you want to stick with a pure array you need to allocate the memory dynamically using malloc, realloc and free. However, you should prefer a std::vector or std::deque for dynamic memory allocation.
Upvotes: 1
Reputation: 76778
You cannot change the length of an array. In C++, you should use an std::vector
for dynamic arrays:
#include <vector>
int main() {
std::vector::size_type length = 10;
std::vector<float> tables(length); // create vector with 10 elements
tables.resize(20); // resize to 20 elemets
tables[15] = 12; // set element at index 15 to value 12
float x = tables[5]; // retrieve value at index 5
}
Upvotes: 14