[英]c++ 2d arrays and pointers to pointers- I don't understand this code
我不理解指向2D數組的指針或指針。 我不明白以下代碼的作用。 任何人都可以逐行向我解釋它在做什么嗎? 對我來說,掌握這個概念確實很重要,但我無法掌握。
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
//i understand that we declare a 2d array
int tD[2][2];
//but then i'm confused why there is a pointer to a pointer when there isn't a pointer in the first place
int **tD2;
//and i am confused what the star after int does
tD2 = new int*[2];
//i think i get this
for(int i = 0; i < 2; i++)
tD2[i] = new int[2];
for(int i = 0; i < 2; i++)
delete [] tD2[i];
//lost here
delete [] tD2;
return 0;
}
我將發表評論以解釋...
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
//i understand that we declare a 2d array
int tD[2][2];
//but then i'm confused why there is a pointer to a pointer when there isn't a pointer in the first place
int **tD2; // A 1D array is an int*; int** makes an array of int*'s, which are themselves arrays (not necessarily all next to each other).
//and i am confused what the star after int does
tD2 = new int*[2]; // allocates memory for two int*'s.
/*
int* a = new int[2];
int** b = new int*[2];
int*** c = new int**[2];
See the pattern? It's one less * than the type.
*/
//i think i get this
for(int i = 0; i < 2; i++)
tD2[i] = new int[2];
for(int i = 0; i < 2; i++)
delete [] tD2[i]; // deallocates each inner array.
//lost here
delete [] tD2; // deallocate the outer array. (i.e., the array that holds the "inner arrays").
return 0;
}
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
//i understand that we declare a 2d array
int tD[2][2];
//but then i'm confused why there is a pointer to a pointer when there isn't a pointer in the first place
int **tD2;
這定義tD2
作為指針(第一*
)的指針(第二*
)向int
。 這對任何東西都沒有用,因為它只是一個指針,還沒有指向任何東西。 直到它指出某事,它才是危險的。
//and i am confused what the star after int does
tD2 = new int*[2];
這會動態地將兩個指針( *
)的數組分配給int
,並將此數組分配給tD2
。 現在, tD2
指向某物並且可以安全使用。 但是,指針數組尚未初始化且很危險。
//i think i get this
for(int i = 0; i < 2; i++)
tD2[i] = new int[2];
該循環為指向上面指向的int
的指針數組中的每個指針動態分配兩個int
的數組。 現在,所有指針都指向某物。
for(int i = 0; i < 2; i++)
delete [] tD2[i];
動態分配的所有內存都應在處理完之后返回到其原始位置,以便可以重用該內存,否則最終程序將耗盡內存。 delete []
返回一個數組,並確保調用了適當的析構函數。 此循環釋放int
數組。
//lost here
delete [] tD2;
出於與上述相同的原因,釋放指向int
的指針數組。
return 0;
}
注意:這是管理2D陣列的可怕方法。 查看您要做的所有工作。 考慮一下忘記或無法返回分配的內存有多么容易。 程序員必須記住尺寸或使用tD2
傳遞尺寸,以確保沒有人超出范圍。
不要這樣 而是使用std::vector
。
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
int main() {
//i understand that we declare a 2d array
int tD[2][2];
vector<vector<int>> tD2(2, // outer vector contains 2 vectors
vector(2)); // inner vector contains 2 ints
return 0;
}
vector
為您照顧記憶。 它知道所有尺寸有多大,因此很難丟失。 它at
有一個方法,它不會讓您越界。 如果您需要變大,它會變大。 采取動態數組! 最重要的是,它具有完全支持搜索,排序和操作的庫。 您必須傻傻不使用vector
。
別傻了
如果您的老師強迫您成為傻瓜,請稱呼他們為傻瓜,然后假裝自己是傻瓜,直到您安全地通過課程為止。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.