How do I declare a 2d array in C++ using new?

2018-12-31 00:00发布

How do i declare a 2d array using new?

Like, for a "normal" array I would:

int* ary = new int[Size]

but

int** ary = new int[sizeY][sizeX]

a) doesn't work/compile and b) doesn't accomplish what:

int ary[sizeY][sizeX] 

does.

21条回答
只靠听说
2楼-- · 2018-12-31 00:06

If your project is CLI (Common Language Runtime Support), then:

You can use the array class, not that one you get when you write:

#include <array>
using namespace std;

In other words, not the unmanaged array class you get when using the std namespace and when including the array header, not the unmanaged array class defined in the std namespace and in the array header, but the managed class array of the CLI.

with this class, you can create an array of any rank you want.

The following code below creates new two dimensional array of 2 rows and 3 columns and of type int, and I name it "arr":

array<int, 2>^ arr = gcnew array<int, 2>(2, 3);

Now you can access elements in the array, by name it and write only one squared parentheses [], and inside them, add the row and column, and separate them with the comma ,.

The following code below access an element in 2nd row and 1st column of the array I already created in previous code above:

arr[0, 1]

writing only this line is to read the value in that cell, i.e. get the value in this cell, but if you add the equal = sign, you are about to write the value in that cell, i.e. set the value in this cell. You also can use the +=, -=, *= and /= operators of course, for numbers only (int, float, double, __int16, __int32, __int64 and etc), but sure you know it already.

If your project is not CLI, then you can use the unmanaged array class of the std namespace, if you #include <array>, of course, but the problem is that this array class is different than the CLI array. Create array of this type is same like the CLI, except that you will have to remove the ^ sign and the gcnew keyword. But unfortunately the second int parameter in the <> parentheses specifies the length (i.e. size) of the array, not its rank!

There is no way to specify rank in this kind of array, rank is CLI array's feature only..

std array behaves like normal array in c++, that you define with pointer, for example int* and then: new int[size], or without pointer: int arr[size], but unlike the normal array of the c++, std array provides functions that you can use with the elements of the array, like fill, begin, end, size, and etc, but normal array provides nothing.

But still std array are one dimensional array, like the normal c++ arrays. But thanks to the solutions that the other guys suggest about how you can make the normal c++ one dimensional array to two dimensional array, we can adapt the same ideas to std array, e.g. according to Mehrdad Afshari's idea, we can write the following code:

array<array<int, 3>, 2> array2d = array<array<int, 3>, 2>();

This line of code creates a "jugged array", which is an one dimensional array that each of its cells is or points to another one dimensional array.

If all one dimensional arrays in one dimensional array are equal in their length/size, then you can treat the array2d variable as a real two dimensional array, plus you can use the special methods to treat rows or columns, depends on how you view it in mind, in the 2D array, that std array supports.

You also can use Kevin Loney's solution:

int *ary = new int[sizeX*sizeY];

// ary[i][j] is then rewritten as
ary[i*sizeY+j]

but if you use std array, the code must look different:

array<int, sizeX*sizeY> ary = array<int, sizeX*sizeY>();
ary.at(i*sizeY+j);

And still have the unique functions of the std array.

Note that you still can access the elements of the std array using the [] parentheses, and you don't have to call the at function. You also can define and assign new int variable that will calculate and keep the total number of elements in the std array, and use its value, instead of repeating sizeX*sizeY

You can define your own two dimensional array generic class, and define the constructor of the two dimensional array class to receive two integers to specify the number of rows and columns in the new two dimensional array, and define get function that receive two parameters of integer that access an element in the two dimensional array and returns its value, and set function that receives three parameters, that the two first are integers that specify the row and column in the two dimensional array, and the third parameter is the new value of the element. Its type depends on the type you chose in the generic class.

You will be able to implement all this by using either the normal c++ array (pointers or without) or the std array and use one of the ideas that other people suggested, and make it easy to use like the cli array, or like the two dimensional array that you can define, assign and use in C#.

查看更多
姐姐魅力值爆表
3楼-- · 2018-12-31 00:07

A dynamic 2D array is basically an array of pointers to arrays. You can initialize it using a loop, like this:

int** a = new int*[rowCount];
for(int i = 0; i < rowCount; ++i)
    a[i] = new int[colCount];

The above, for colCount= 5 and rowCount = 4, would produce the following:

enter image description here

查看更多
像晚风撩人
4楼-- · 2018-12-31 00:08

I presume from your static array example that you want a rectangular array, and not a jagged one. You can use the following:

int *ary = new int[sizeX * sizeY];

Then you can access elements as:

ary[y*sizeX + x]

Don't forget to use delete[] on ary.

查看更多
伤终究还是伤i
5楼-- · 2018-12-31 00:09

How to allocate a contiguous multidimensional array in GNU C++? There's a GNU extension that allows the "standard" syntax to work.

It seems the problem come from operator new []. Make sure you use operator new instead :

double (* in)[n][n] = new (double[m][n][n]);  // GNU extension

And that's all : you get a C-compatible multidimensional array...

查看更多
闭嘴吧你
6楼-- · 2018-12-31 00:09

declaring 2D array dynamically:

    #include<iostream>
    using namespace std;
    int main()
    {
        int x = 3, y = 3;

        int **ptr = new int *[x];

        for(int i = 0; i<y; i++)
        {
            ptr[i] = new int[y];
        }
        srand(time(0));

        for(int j = 0; j<x; j++)
        {
            for(int k = 0; k<y; k++)
            {
                int a = rand()%10;
                ptr[j][k] = a;
                cout<<ptr[j][k]<<" ";
            }
            cout<<endl;
        }
    }

Now in the above code we took a double pointer and assigned it a dynamic memory and gave a value of the columns. Here the memory allocated is only for the columns, now for the rows we just need a for loop and assign the value for every row a dynamic memory. Now we can use the pointer just the way we use a 2D array. In the above example we then assigned random numbers to our 2D array(pointer).Its all about DMA of 2D array.

查看更多
公子世无双
7楼-- · 2018-12-31 00:09
int** ary = new int[sizeY][sizeX]

should be:

int **ary = new int*[sizeY];
for(int i = 0; i < sizeY; ++i) {
    ary[i] = new int[sizeX];
}

and then clean up would be:

for(int i = 0; i < sizeY; ++i) {
    delete [] ary[i];
}
delete [] ary;

EDIT: as Dietrich Epp pointed out in the comments this is not exactly a light weight solution. An alternative approach would be to use one large block of memory:

int *ary = new int[sizeX*sizeY];

// ary[i][j] is then rewritten as
ary[i*sizeY+j]
查看更多
登录 后发表回答