2012-11-09 136 views
0

我有一個GLOBE結構,其中包含地球上每個經緯度單元的幾個參數。 我有一個三重指針如下:指向結構的免費3D指針

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

struct GLOBE { 
    double *var; 
}; 

其中malloc_2d是一個自定義函數來分配下面定義的2D陣列。地圖可以遍歷所有的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具有其它動態分配的一維和二維陣列(例如雙*變量)。所以當我不得不釋放每個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); 

然而,這似乎並沒有工作。我應該改變什麼? 謝謝!

+2

您需要在此發佈更多代碼,包括'GLOBE'結構的定義和'malloc_2d'數組的實現。你的代碼......「感覺很奇怪」...... – lerosQ

+0

修改後的代碼包含malloc_2d和GLOBE的定義 – user308827

回答

0

malloc_2d()(複製粘貼?)功能似乎被正確地寫入,但在這裏發佈的代碼的剩下的只是完成nonsese ...

我會在這裏發佈的類似的東西的工作示例你想這樣做,使用輸入代碼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; 
}