簡體   English   中英

動態分配內存

[英]Dynamically allocating memory

我是C ++和編程的新手,所以如果這是一個小問題,我深表歉意。我正在嘗試初始化2個大小為[600] [600]的數組並鍵入str,但是我的程序不斷崩潰。我認為這是因為這2個數組超出了堆棧的內存限制。此外,N由用戶指定,因此我不確定我是否可以在此處使用new,因為它不是常量表達式。

我的代碼:

#include<iostream>

using namespace std;

struct str {
int x;
int y;
int z;
};
int main(){
cin>>N;
str  Array1[N][N]; //N can be up to 200
str  Array2[N][N];
};

我怎么能在堆中初始化它們?我知道對於一維數組我可以使用向量,但我不知道這是否可以以某種方式應用於二維數組。

二維數組如何在C ++中工作

一維數組易於實現和取消引用。 假設數組名稱為arr ,則只需進行一次取消引用即可訪問元素。

二維或二維以上的數組,無論是動態數組還是基於堆棧的數組,都需要更多步驟來創建和訪問。 為了在矩陣和矩陣之間進行類比,如果arr是2D數組,並且您想訪問特定元素,則說arr[row][col] ,此步驟中實際上有2個取消引用。 第一個, arr[row] ,使您可以訪問該row的個排col元素。 第二個也是最后一個, arr[row][col]到達您需要的確切元素。

因為arr[row][col]需要2個解引用才能獲得訪問權限,所以arr不再是指針,而是指向指針的指針 關於上述內容,第一個解引用為您提供了指向特定行(一維數組)的指針,而第二個解引用為您提供了實際元素。

因此,動態2D數組要求您有一個指向指針的指針。

分配運行時給定大小的動態2D數組

首先,您需要創建一個指向所選擇數據類型的指針的指針數組。 由於您的stringstring ,因此,一種實現方式是:

std::cin >> N;
std::string **matrix = new string*[N];

您已經分配了一個行指針數組。 最后一步是遍歷所有元素並自己分配列:

for (int index = 0; index < N; ++index) {
    matrix[index] = new string[N];
}

現在,您可以像使用普通2D網格一樣取消引用它:

// assuming you have stored data in the grid
for (int row = 0; row < N; ++row) {
    for (int col = 0; col < N; ++col) {
        std::cout << matrix[row][col] << std::endl;
    }
}

需要注意的一件事:動態數組比常規的基於堆棧的對應數組在計算上更昂貴。 如果可能,請選擇使用STL容器,例如std::vector

編輯:要釋放矩陣,請“向后”:

// free all the columns
for (int col = 0; col < N; ++col) {
    delete [] matrix[col];
}

// free the list of rows
delete [] matrix;

通常,您可以使用“ new”運算符來初始化堆中的內存。 希望這可以幫到你:

// Example program
#include <iostream>

struct str {
int x;
int y;
int z;
};

int main()
{
  int N;
  std::cin>>N;
  str  **Array1 = new str*[N]; //N can be up to 200
  for (int i = 0; i < N; ++i) {
    Array1[i] = new str[N];
  }
  // set value
  for (int row = 0; row < N; ++row) {
    for (int col = 0; col < N; ++col) {
        Array1[row][col].x=10;
        Array1[row][col].y=10;
        Array1[row][col].z=10;
    }
  }
  // get value
  for (int row = 0; row < N; ++row) {
    for (int col = 0; col < N; ++col) {
        std::cout << Array1[row][col].x << std::endl;
        std::cout << Array1[row][col].y << std::endl;
        std::cout << Array1[row][col].z << std::endl;
    }
  }
}

想要使用new運算符在C ++中分配2D數組時,必須聲明(*pointer-to-array)[N] ,然后使用new type [N][N];進行分配new type [N][N];

例如,可以聲明和分配Array1 ,如下所示:

#define N 200

struct str {
    int x, y, z;
};

int main (void) {

    str (*Array1)[N] = new str[N][N];  /* allocate */

    /* use Array1 as 2D array */

    delete [] Array1;                  /* free memory */
}

但是,理想情況下,您希望讓C ++容器庫類型vector處理您的內存管理。 例如,您可以:

#include<vector>
..
std::vector <std::vector <str>> Array1;

然后填充Array1 ,填充一個臨時的std::vector<str> tmp; Array1 對於str每一行(一維數組),然后是Array1.push_back(tmp); 將填充的tmp向量添加到Array1 您的訪問仍然可以是2D索引(例如Array1[a][b].x, Array1[a][b].y, ... ,但是您可以從容器提供的自動內存管理中受益。與自己處理內存相比,錯誤發生的可能性要小。

暫無
暫無

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

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