Changing the length of an array in C ++

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 an array in C ++:

I cannot declare an array something like this:

int length=10;

float newTables[length]; // error C2133: 'newTables' : unknown size

Thanks in advance.

+3
source share
4 answers

If you perfectly determine the size of the array at build time, you can use #define

#DEFINE ARRAY_SIZE 20
float tables[ARRAY_SIZE];

Or, if you need to specify the size of the array at runtime, use the new

float* newtables;
newtables = new float[20];
+1
source

You cannot change the length of an array. In C ++, you should use std::vectorfor 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
}
+14
source
+1

++. , , :

const int length=10;
float newTables[length];

, , . "" .

, .

0

All Articles