Initializing a 2D array with a dynamic number of rows and a fixed number of columns. C ++

I had a problem creating my 2D C ++ dynamic array. I want it to have a dynamic number (like numR) of "rows" and a fixed (like 2) number of "columns".

I tried to do it like this:

const numC = 2;
int numR;
numR = 10;
double *myArray[numC];
myArray = new double[numR];

Unfortunately, it does not work. Can this be done in this way?

Of course, I could use double **myArrayand initialize it as if both dimensions were dynamic (using numC as a limiter in the loop), but I would like to avoid it if possible.

Thanks in advance.

+3
source share
4

?

:

double (*myArray)[numC] = new double[numR][numC];
// ...
delete[] myArray;

, 5.3.4 ยง5 :

new int[i][10] int (*)[10]

, C . , . :

#include <vector>
#include <array>

std::vector<std::array<double, numC> > vec(numR);
// ...
// no manual cleanup necessary

std::array std::tr1::array boost::array, .

+6

std::vector :

std::vector<std::vector<int> > my2Darray(2, std::vector<int>(10));
my2Darray[0][0] = 2;
+2

, .

, :

double *myArray[numC];
for (int i = 0; i < numC; i++) {
    myArray[i] = new double[numR];
}

// some code...

// Cleanup:
for (int i = 0; i < numC; i++) {
    delete [] myArray[i];
}

This declares an array of pointers (to double) with elements numC, and then creates an array doublewith numRelements for each column in myArray. Remember to free up memory when you are done with it, or you will have memory leaks.

+1
source

Your indexes should be string and then columns.

double** myArray = new double*[numR];
for( unsigned int i = 0; i < numR; i++ ) {
    myArray[i] = new double[numC];
}

Access to row 2, column 5:

myArray[2][5];
-1
source

Source: https://habr.com/ru/post/1776462/


All Articles