簡體   English   中英

C ++ 2D指針數組

[英]C++ 2D pointer array

我很困惑如何分配指針的“ 2D數組”。

經過一些試驗,我設法分配了一些似乎有效的東西,但是我不知道為什么,所以解釋會很棒。

這是我的整個代碼:

#include <iostream>


using namespace std;


int main() {


int *** ptr = (int ***)malloc(sizeof(int)* 100*100);
for (int i = 0; i < 100; ++i)
{
    ptr[i] = (int**)malloc(sizeof(int) * 100);
    for (int j = 0; j < 100; ++j)
        ptr[i][j] = (int*)malloc(sizeof(int) * 100);
}


cout << *ptr[20][20] << endl;
cout << *ptr[99][20] << endl;


}

好的,他們正在打印“垃圾值”,但看起來與我嘗試過的其他方法不同。
因此,如果我沒有誤解,那么它應該等效於array [100] [100]。

我的問題是,為什么每個“級別”的指針都必須具有大小。

在這一行:

for (int j = 0; j < 100; ++j)
        ptr[i][j] = (int*)malloc(sizeof(int) * 100);
}

在我看來,我們正在使2d數組的每個坐標(我知道這與2d array不同)可以容納100個整數,而我只想保存一個整數。

但是如果我這樣刪除它

for (int j = 0; j < 100; ++j)
        ptr[i][j] = (int*)malloc(sizeof(int));
}

然后我的程序停止工作。 為什么呢

 ptr[i] = (int**)malloc(sizeof(int) * 100); 

ptr[i]指向一個可以容納100個int對象的存儲塊。 但是,您的程序嘗試將100個int**對象填充到該內存塊中。 如果sizeof(int**) > sizeof(int)可能是,則溢出分配的內存。 該行為是不確定的。

另一方面, sizeof(int)* 100*100可能比100個int***對象所需要的更多。


C ++引入了一項稱為新表達式的功能,該功能為您隱式計算分配的對象或對象數組所需的內存。 使用它們來避免此類錯誤。 他們(幾乎)使malloc在C ++中過時了。

我已經接受使用向量是解決我的問題的最佳解決方案,但是萬一將來有人需要它,這就是我想要做的:

int *** p2 = (int ***)malloc(sizeof(int **)* 100);
for (int i = 0; i < 100; i++)
p2[i] = (int **)malloc(sizeof(int *)* 100);


for (int i = 0; i < 100; i++) {
    for (int j = 0; j < 100; j++) {
        p2[i][j] = (int *)malloc(sizeof(int));

    }
}

暫無
暫無

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

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