簡體   English   中英

C++ 中的動態多維數組

[英]Dynamic Multidimensional Array in C++

該程序應該采用一個維度 n 並制作一個 nxn 維度的多維數組,我知道它必須使用new[ ]運算符來完成,因此它應該使用指針來完成,我在互聯網上找到了很多方法,但我我是這個話題的新手,不能很好地理解它們是如何工作的,這是我發現聲稱可以工作的代碼之一:

main()
{
    double n;
    cout<<"Enter the n dimension to the matrix[nxn]: ";
    cin>>n;
    matrix=new int*[n];
    int *data=new int[n*n];
    for(i=0;i<n;i++)
      matrix[i]=&data[i*n];
}

我的問題是:這段代碼對嗎? 如果是這樣,它是如何工作的? 否則,哪些代碼有效? (如果你能和一點解釋,我會很感激)

您不應該使用原始指針,最好使用std::vector

#include <iostream>
#include <vector>

int main() {
    int n;
    std::cin << n;

    std::vector<std::vector<int>> matrix(n, std::vector<int>(n));
    // Do whatever with matrix

    return 0;
}

動態分配的正確方法是這樣的(如果只涉及數組):

matrix = new int*[n];        //create an array of 'n' pointers
for(int i = 0;i < n;i++)
    matrix[i] = new int[n];  //allocate memory equivalent of 'n' ints to each of the 'n' pointers

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM