如何在C编程中释放浮动**

Pie*_*RTY 2 c free gcc compiler-errors

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

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);
}
Run Code Online (Sandbox Code Playgroud)

我得到了那个我不明白的错误......:

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
Run Code Online (Sandbox Code Playgroud)

如果有人可以帮助我

我的代码如下:

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);
Run Code Online (Sandbox Code Playgroud)

Cor*_*ien 5

你试图释放每个人float而不是分配的指针.

假设你已经分配了这样的矩阵:

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

然后你需要释放每个内部指针,然后释放外部指针,如下所示:

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

free(that);
Run Code Online (Sandbox Code Playgroud)