gpt4 book ai didi

c - 使用函数的免费双指针

转载 作者:太空宇宙 更新时间:2023-11-04 06:32:04 24 4
gpt4 key购买 nike

所以我使用以下函数为双指针创建并分配了内存:

void mallocDoubleArr(double ***arr, int size)
{
printf("Here: %d", size);
int i, j;

*arr = malloc(size * sizeof(double*));

for(i = 0; i < size; i++)
{
(*arr)[i]= malloc(size*sizeof(double));
for (j = 0; j < size; j++)
{
(*arr)[i][j] = 0;
}
}
}

然后我调用函数使用:

    double **G; //Create double pointer to hold 2d matrix

mallocDoubleArr(&G, numNodes);

现在我的问题是如何编写释放内存的函数?

我试过这样的:

void freeDoubleArr(double ***arr, int size)
{
int i, j;

for (i = 0; i < size; i++)
for (j = 0; j < size; j++)
free((arr)[i]);
free(arr);
}

最佳答案

您似乎想将指针的地址传递给您的 freeDoubleArr喜欢freeDoubleArr(&G, numnodes) (我宁愿称之为 deleteDoubleArr )。那么你需要有

void freeDoubleArr(double ***arrptr, int size)
{
double** arr = *arrptr;
for (int i = 0; i < size; i++)
free(arr[i]);
free (arr);
*arrptr = NULL;
}

但是,您可以决定您的方阵不表示为指向数组的指针数组,而只是表示为普通数组。也许使用 flexible array members (C99 及以后的)喜欢

struct matrix_st {
unsigned size;
double arr[]; /* flexible array of size*size elements */
};

可能会有用,因为约定 arr实际上是一个 size*size 的数组元素(每个都是 double )。

然后您可以定义快速访问和修改器内联函数。

inline double get_element(struct matrix_st *m, int i, int j) {
assert (m != NULL);
unsigned s = m->size;
assert (i>=0 && i<s && j>=0 && j<s);
return m->arr[s*i+j];
}

inline void put_element(struct matrix_st* m, int i, int j, double x) {
assert (m != NULL);
unsigned s = m->size;
assert (i>=0 && i<s && j>=0 && j<s);
m->arr[i*s+j] = x;
}

在使用 <assert.h> 进行优化时(参见 assert(3) ...)并使用 -DNDEBUG 进行编译上面的访问器 get_element和突变体 put_element可能会比您的代码更快。

矩阵的创建只是(创建一个零矩阵):

struct matrix_st* make_matrix (unsigned size) {
struct matrix_st* m = malloc(sizeof (struct matrix_st)
+ size*size*sizeof(double);
if (!m) { perror("malloc"); exit(EXIT_FAILURE); };
m->size = size;
memset(m->arr, 0, sizeof(double)*size*size);
return m;
}

然后用户只需调用一次 free释放这样一个矩阵。

顺便说一句,如果在 Linux 上编码,用 gcc -Wall -g 编译并使用 valgrind内存泄漏检测器和 gdb调试器。

关于c - 使用函数的免费双指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19526356/

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