gpt4 book ai didi

c++ - 如何完全删除二维指针数组

转载 作者:太空狗 更新时间:2023-10-29 20:37:29 24 4
gpt4 key购买 nike

我在 C++ 中有一个 2D 指针矩阵,例如,

typedef unsigned char  U8;
typedef unsigned int U32;
int M=10;
int m_L=8;
U8** A = new U8*[M];
for (U32 i = 0; i < M; ++i)
{
A[i] = new U8[m_L];
}

在A0中设置值后,我会写一个函数来决定删除或不删除A中的M-2行,取决于随机数是0还是1

void delete_or_not(U8** A,int M) 
{
if (rand_num==1){
for (U32 index = M-2; index < M; ++index){
delete[] A[index];
}
}
}

现在,在 main 函数(包含 A 内存分配)中,我想释放/删除为 A 分配的内存。我可以使用代码

//free A matrix
for (U32 i = 0; i < M; ++i)
{
if (i < m_L)
{
delete[] A[i];
A[i] = NULL;
}
}
delete[] A;
A = NULL;

我的问题是,我不知道 A 是否删除 (M-2) 行。因此,如果我的随机数为 0,上面的代码确实会删除所有内存。这意味着,如果在 delete_or_not 函数中删除了 M-2 行,上面的代码只会删除正确的内存。怎样才能完美删除A矩阵。谢谢

最后,我的完整代码是

typedef unsigned char  U8;
typedef unsigned int U32;
int M=10;
int m_L=8;
U8** A = new U8*[M];
for (U32 i = 0; i < M; ++i)
{
A[i] = new U8[m_L];
}
delete_or_not(A,M);
//free A matrix
//Way 1: will miss M-2 row if delete_or_not function did not delete 2 rows.
// It only correct if rand_num=1
for (U32 i = 0; i < M; ++i)
{
if (i < m_L)
{
delete[] A[i];
A[i] = NULL;
}
}
delete[] A;
A = NULL;

//Way 2- It will correct if the size of A is M by M

for (U32 i = 0; i < M; ++i)
{
delete[] A[i];
A[i] = NULL;
}
delete[] A;
A = NULL;

最佳答案

只需将删除的元素设置为NULL一切都会好起来的:

void delete_or_not(U8** A,int M) 
{
if (rand_num==1){
for (U32 index = M-2; index < M; ++index){
delete[] A[index];
A[index] = NULL;
}
}
}

此外,这不是很有用:

for (U32 i = 0; i < M; ++i)
{
if (i < m_L)
{
delete[] A[i];
A[i] = NULL;
}
}

前进没有意义i从 0 到 M如果你只在 i 时“工作”小于m_L .


但实际上,在 C++ 中你可能应该使用 std::vector<std::vector<U8>>相反,简单地 erasepop_back摆脱“行”。

关于c++ - 如何完全删除二维指针数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34542532/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com