- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我正在用c编写一个基本的矩阵库,矩阵数据结构如下所示:
typedef struct Matrix{
int rows;
int cols;
double complex *matrix;
} Matrix;
以及相应的初始化矩阵的函数和释放指针的函数(类似于c++中的构造函数和析构函数)
Matrix* InitializeMatrix(int r, int c){
Matrix* mat = malloc(sizeof(Matrix));
mat->rows = r;
mat->cols = c;
mat->matrix = (double complex *)malloc(r * c * sizeof(double complex));
return mat;
}
int DeleteMatrix(Matrix *mat){
mat->rows = 0;
mat->cols = 0;
free(mat->matrix);
mat->matrix = 0;
return 0;
}
这是主要问题。假设我有两个函数
Matrix* fun1(Matrix* input){
//some operations
Matrix* mat = InitializeMatrix(r, c);
//some operations
return mat;
}
Matrix* fun2(Matrix* input){
//some operations
Matrix* mat = InitializeMatrix(r, c);
//some operations
return mat;
}
现在我有另一个函数想要嵌套fun1
和fun2
Matrix* fun3(Matrix* input){
return fun2(fun1(input));
}
通常当我调用一个函数时,我必须调用 DeleteMatrix
来释放内存,但是在 fun2(fun1(input))
中,对矩阵的引用由 fun1(input)
生成的代码不会保存,也无法释放。我知道我可以创建一个中间变量来进行引用,但我想保留嵌套函数调用,因为它简洁直观。我的整体设计有问题吗?如何克服这个问题?
最佳答案
一种选择是更改函数原型(prototype),以便 fun1()
和 fun2()
接受第二个参数,它是指向 Matrix
的指针.然后你可以改变函数体,这样一个新的 Matrix
如果此参数为 NULL
则分配, 否则 output
Matrix
用来。例如:
Matrix* fun1(Matrix* input, Matrix* output){
//some operations
Matrix* mat;
if (output == NULL){
mat = InitializeMatrix(input->rows, input->cols);
} else {
mat = output;
}
//some operations
return mat;
}
这里我假设 r
和 c
未声明的原始函数的行数和列数是 input
的行数和列数。 Matrix
.如果你想要fun1()
分配一个新的 Matrix
,这样调用它:
Matrix* result = fun1(input, NULL);
如果你想使用预分配的 Matrix
:
Matrix* mtrx = InitializeMatrix(3, 3);
mtrx = fun1(input, mtrx);
如果你想链接在一起fun1()
和 fun2()
:
mtrx = fun2(fun1(input, mtrx), mtrx);
尽管让外部函数调用进行分配可能会更好;这样mtrx
总是一个中间结果,你只需要创建一个新的Matrix
获得新结果的指针。请注意,您仍然需要为 mtrx
分配空间。 :
result = fun2(fun1(input, mtrx), NULL);
您可以将更多功能链接在一起,但这可能会越过阈值而变得不当:
result = fun3(fun2(fun1(input, mtrx), mtrx), NULL);
另外,请注意您的 DeleteMatrix()
功能有问题。无需将字段清零,您需要 free(mat)
以及free(mat->matrix)
:
int DeleteMatrix(Matrix* mat){
free(mat->matrix);
free(mat);
return 0;
}
关于c - 删除嵌套函数调用中生成的中间指针的最佳做法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41613761/
如果您想分享更多信息,可以在这里找到整个资源 指针: https://github.com/sergiotapia/DreamInCode.Net 基本上,我的API将为其他开发人员提供
关闭。这个问题需要更多focused .它目前不接受答案。 想改进这个问题吗? 更新问题,使其只关注一个问题 editing this post . 关闭 5 年前。 Improve this qu
我不是 SCM 工具的经验丰富的用户,尽管我确信它们的用处,当然。 我在以前的工作中使用了一些不起眼的商业工具,在当前的工作中使用了 Perforce,并在我的小型个人项目中使用了 TortoiseS
所以我想知道一些我应该避免在 javascript 中做的事情以获得良好的 SEO 排名。在我的下一个站点中,我将广泛使用 jquery 和 javascript,但不想牺牲 SEO。那么您认为我应该
基本上,我想知道什么是避免 future CSS 代码出现问题和混淆的最佳方法... 像这样命名 CSS 属性: div#content ul#navigation div.float-left (真
我是一名优秀的程序员,十分优秀!