我有一个结构globe,它包含了GLOBE上每个后面的单元格的几个参数。我有一个三重指针,如下所示:
data->map = (struct GLOBE ***)malloc_2d(NROWS, NCOL, sizeof(struct GLOBE *));
struct GLOBE {
double *var;
};其中malloc_2d是一个自定义函数,用于分配下面定义的二维数组。地图可以遍历全球的所有地图。
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有其他动态分配的一维和二维数组(例如,双*var)。因此,当我必须释放所有全局内存和每个全局内动态分配的内存时,我会遇到错误。
具体地说,我尝试:
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);然而,这似乎不起作用。我应该改变什么?谢谢!
发布于 2012-11-10 08:14:18
malloc_2d() (复制-粘贴?)函数似乎是正确编写的,但这里发布的其余代码完全是无用的……
我将在这里发布一个您想要做的类似事情的工作示例,使用此处的enter代码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;
}https://stackoverflow.com/questions/13315125
复制相似问题