我正在嘗試洗掉我的 2D 陣列,但是當我嘗試洗掉它時總是出現錯誤,我們必須向后作業,所以我首先洗掉元素,然后是列陣列,然后是行陣列。這是我的類 MyMatrix 中建構式的代碼:
private:
int m; //rows
int **ptr; //ptr to first dimension
int n; // columns
public:
MyMatrix() //constructor
{
m = 0;
n = 0;
ptr = new int*[m];
int *length_arr = new int[m];
for (int i = 0; i <= m-1; i )
{
*(ptr i) = new int[n];
*(length_arr i) = n;
}
}
我的解構式如下所示:
for(int i = 0; i <= m-1; i )
{
for (int j = 0; j <= n-1; j )
{
delete ((*(ptr i)) j);
}
delete[] *(ptr i);
}
delete[] ptr;
我得到的錯誤是:
assg7(2677,0x100de3d40) malloc: *** error for object 0x12d606804: pointer being freed was not allocated
我已經絞盡腦汁想在哪里解決這個問題,對于背景關系,我正在做一個運算子多載的賦值。我特別需要一個洗掉函式來為我的 = 賦值多載正常作業,因為我想洗掉并再次重新分配記憶體以等同于兩個矩陣,但終端顯示 malloc 錯誤,因此沒有等同于矩陣。有關其他資訊,請參閱我的 = 多載代碼:
void operator = (const MyMatrix &obj)
{
if(n == obj.n && m == obj.m)
{
//for loop to equate elements in this-> to the elements of the passed object
}
else
{
for(int i = 0; i <= m-1; i )
{
for (int j = 0; j <= n-1; j )
{
delete ((*(ptr i)) j);
}
delete[] *(ptr i);
}
delete[] ptr;
// the code for assigning new memory according to the passed objects rows and colums goes here
//then for loop to equate elements in this-> to the elements of the passed object
}
}
謝謝。
uj5u.com熱心網友回復:
您有 的兩個“級別” new,因此三個“級別”的delete不可能是正確的。
使用索引而不是指標算術詳細說明您的洗掉回圈:
First iteration:
delete ptr[0] 0;
delete ptr[0] 1;
...
delete ptr[0] n-1;
delete [] ptr[0];
Second iteration:
delete ptr[1] 0;
delete ptr[1] 1;
...
delete ptr[1] n-1;
delete [] ptr[1];
您正在傳遞delete一個指向 的第一個元素的ptr[0]指標,一個指向 的第二個元素的ptr[0]指標,一個指向 的第三個元素的指標ptr[0],...
但是您分配的內容是ptr[0], ptr[1], ... ptr[m-1],而不是它們的單個元素。
洗掉最里面的洗掉回圈。
(當您可以使用索引時,不要亂用指標演算法。)
uj5u.com熱心網友回復:
如果默認設定為 0,我不知道您希望如何按 m 長度分配記憶體空間。對我來說,您似乎設定了 m = 0,然后嘗試按 0 分配長度,或者您如何控制尺寸的長度?
也許將您的建構式編輯為:
MyMatrix(int m, int n)
{
this->m = m;
this->n = n;
...
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/360391.html
