Multi-dimensional array and pointers in C++?

后端 未结 6 1511
悲哀的现实
悲哀的现实 2020-12-20 09:35
int *x = new int[5]();

With the above mentality, how should the code be written for a 2-dimensional array - int[][]?

i         


        
6条回答
  •  不思量自难忘°
    2020-12-20 10:15

    There is no new[][] operator in C++. You will first have to allocate an array of pointers to int:

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

    Then iterate over that array. For each element, allocate an array of ints:

    for (std::size_t i = 0; i < 5; ++i)
        x[i] = new int[5];
    

    Of course, this means you will have to do the inverse when deallocating: delete[] each element, then delete[] the larger array as a whole.

提交回复
热议问题