0

我有一个结构 GLOBE,其中包含地球上每个纬度单元的几个参数。我有一个三重指针,如下所示:

data->map = (struct GLOBE ***)malloc_2d(NROWS, NCOL, sizeof(struct GLOBE *));

struct GLOBE {
  double *var;
};

其中 malloc_2d 是一个自定义函数,用于分配下面定义的二维数组。map 可以遍历所有 GLOBE。

void** malloc_2d (size_t nrows, size_t ncols, int elementsize) {
size_t i;
void ** ptr;
if ( (ptr = (void**)malloc(nrows * sizeof(void *))) == NULL ) {
  fprintf(stderr, "malloc_2d: out of memory\n");
  exit(1);
}
if ( (ptr[0] = malloc(nrows * ncols * elementsize)) == NULL ) {
  fprintf(stderr, "malloc_2d: out of memory\n");
  exit(1);
}

for (i=1; i<nrows; i++) 
  ptr[i] = (char*)ptr[0] + i * ncols * elementsize;
  return ptr;

}

GLOBE 还有其他动态分配的 1D 和 2D 数组(例如 double *var)。因此,当我必须释放所有 GLOBE 和每个 GLOBE 内动态分配的内存时,我遇到了错误。

具体来说,我尝试:

for(size_t i = 0; i < data->n_lat; i++)
    for(size_t i = 0; i < data->n_lat; i++) {
        free(data->map[i][j]->var);

free(data->map);

但是,这似乎不起作用。我应该改变什么?谢谢!

4

1 回答 1

0

( malloc_2d()copy-paste?) 函数似乎是正确编写的,但这里发布的其余代码只是完全废话......

我将在此处使用输入代码在此处发布您想要执行的类似操作的工作示例malloc_2d()。我建议你玩弄它,直到你掌握 C 中指针的基本概念。

此外,请随时询问(明确)有关代码的问题。

#include <stdio.h>
#include <stdlib.h>

#define NROWS 8
#define NCOL 6

struct GLOBE {
  double **var;
};

void** malloc_2d (size_t nrows, size_t ncols, int elementsize)
{
        // code posted
}

void free_2d (void ** ptr, size_t n_rows)
{
    int i;

    // free the "big part"
    free(ptr[0]);

    // free the array of pointers to the rows
    free(ptr);
}

int main()
{
    struct GLOBE gl;
    int i, j;

    gl.var = (double **)malloc_2d(NROWS, NCOL, sizeof(double));

    for (i = 0; i < NROWS; ++i) {
        for (j = 0; j < NCOL; ++j) {
            gl.var[i][j] = i * j;
            printf("%0.1f ", gl.var[i][j]);
        }
        printf("\n");
    }

    free_2d((void **)gl.var, NROWS);

    return 0;
}
于 2012-11-10T00:14:17.793 回答