如何在 C 编程中释放一个 float**

how to free a float** in C programming

我刚刚编写了一个代码来释放浮动的多维选项卡:

void matrix_destroy(float **that)
{
        for (int y = 0; y < 3; ++y) {
            for (int x = 0; x < 3; ++x) {
                free (that[y][x]);
            }
        }
        free (that);
}

我收到了一个我不明白的错误...:[=​​13=]

SRC/creators_destructors.c: In function ‘matrix_destroy’: SRC/creators_destructors.c:56:10: error: incompatible type for argument 1 of ‘free’
free (that[y][x]);
      ^~~~ In file included from ./include/mylibs.h:13:0,
             from SRC/creators_destructors.c:8: /usr/include/stdlib.h:448:13: note: expected ‘void *’ but argument is of type ‘float’  extern void free (void *__ptr) __THROW;
         ^~~~
# cc1 0.01 0.00
make: *** [<builtin>: SRC/creators_destructors.o] Error 1

如果有人可以帮助我

我的代码如下:

float **my_matrix;

    if ((my_matrix = malloc(sizeof(float *) * 3)) == NULL)
        perror("");
    for (int i = 0; i < 3; ++i) {
        if ((my_matrix[i] = malloc(sizeof(float) * 3)) == NULL)
            perror("");
    }
    for (int y = 0; y < 3; ++y) {
        for (int x = 0; x < 3; ++x) {
            if (x == 0 && y == 0)
                my_matrix[y][x] = 1;
            else if (x == 1 && y == 1)
                my_matrix[y][x] = 1;
            else if (x == 2 && y == 2)
                my_matrix[y][x] = 1;
            else
            my_matrix[y][x] = 0;
        }
    }
    return (my_matrix);

这一行:

free (that[y][x]);

您没有传递指向 free 的指针。您正在传递 float。变量 that 的类型为 float **,因此 that[y] 的类型为 float *that[y][x] 的类型为 float.

查看您的分配代码,您将单个 malloc 用于指针数组,然后对 malloc 一个或多个 float 数组进行单个循环。所以你应该以相反的顺序解除分配:

for (int y = 0; y < 3; ++y) {
    free (that[y]);
}
free (that);

通常,用于释放的代码应该反映正在分配的冷量。

您正在尝试释放每个个体 float 而不是分配的指针。

假设您已分配矩阵执行如下操作:

float **that = malloc(3 * sizeof *that);
for (int i = 0; i < 3; i++) {
    that[i] = malloc(3 * sizeof **that);
}

然后你需要释放每个内部指针,然后释放外部指针,像这样:

for (int i = 0; i < 3; i++) {
    free(that[i]);
}

free(that);