gpt4 book ai didi

c++ - 将指针传递给要删除的函数的正确方法是什么?

转载 作者:太空狗 更新时间:2023-10-29 23:33:58 25 4
gpt4 key购买 nike

我有一个声明为 int **matrix 的矩阵,我知道将它传递给函数以分配内存的正确方法应该是这样的:

void AllocMat(int ***mat, int size);

但现在我需要在另一个函数中删除这些内存并且不确定要传递什么:

void DeallocMat(int **mat, int size);

void DeallocMat(int ***mat, int size);

我认为第二个应该是正确的,但是在我尝试时两种方式都没有出现段错误。

最佳答案

问题被标记为 C++,但答案仅使用 C 子集...

嗯,首先,我会反对整个事情。创建一个封装矩阵的类并将其分配到一个 block 中,提供 operator()(int,int) 以访问元素...

回到问题。在 C++ 中,您应该使用引用而不是指针来允许函数更改参数,因此您的原始分配签名应该是:

void AllocMat(int **&mat, int size);

然后这样调用它:

int **matrix = 0;
AllocMat( matrix, 5 );

或者更好,只是返回指针:

int **AllocMat( int size );
int **matrix = AllocMat( 5 );

对于deallocation函数,由于不需要修改外层指针,可以直接使用:

void DeallocMat( int**mat, int size ); // size might be required to release the 
// internal pointers

现在,对于 C++ 解决方案的草图:

template <typename T>                   // no need to limit this to int
class square_matrix {
const unsigned size;
T * data;
public:
square_matrix( unsigned size ) : size(size), data( new T[size*size]() ) {}
square_matrix( matrix const & m ) : size( m.size ), data( new T[m.size*m.size] ) {
std::copy( m.data, m.data+size*size, data );
}
~matrix() {
delete [] data;
}
T const & operator()( unsigned x, unsigned y ) const {
// optional range check and throw exception
return data[ x + y*size ];
}
void set( unsigned x, unsigned y, T const & value ) {
// optional range check and throw exception
data[ x + y*size ] = value;
}
};

关于c++ - 将指针传递给要删除的函数的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7126028/

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