2016-06-11 72 views
2

大家好,我有我的代碼中的一些問題:雙指針的釋放和指針的問題

這是一個矩陣分配功能:

matrix_type** matrix_allocation(MATRIX* matrix, int* rows_size, int* cols_size) 
//this function allocates dynamically a matrix and verify its allocation 
{ 
    int i; 
    matrix->n_rows=0; 
    matrix->n_cols=0; 
    matrix->pp_matrix=(matrix_type**)calloc(*rows_size,sizeof(matrix_type*)); 
    i=0; 
    while(i<*rows_size) 
    { 
     matrix->pp_matrix[i]=calloc(*cols_size,sizeof(matrix_type)); 
     i++; 
    } 
    matrix->n_rows=*rows_size; 
    matrix->n_cols=*cols_size; 
    return matrix->pp_matrix; 
} 

這是我釋放函數:

void matrix_deallocation(MATRIX* matrix) 
//this function deallocates a matrix 
{ 
    int i; 
    i=0; 
    while(i<matrix->n_cols) 
    { 
     free(matrix->pp_matrix[i]); 
     i++; 
    } 
    free(matrix->pp_matrix); 
} 

其中MATRIX結構是

typedef int matrix_type; 
typedef struct{ 
    int n_rows; 
    int n_cols; 
    matrix_type** pp_matrix; 
}MATRIX; 

如何我調用釋放函數主:

matrix_deallocation(&table); 

此功能取消分配只有一半的矩陣,爲什麼呢?

Screen

+1

你有沒有聽說過'for'循環 - 使代碼比使用'while'循環 –

+1

@Simone TheAlmighty Cicerello你有沒有分配更具可讀性矩陣按行或按列? –

回答

2

看來你指的是以下

void matrix_deallocation(MATRIX* matrix) 
//this function deallocates a matrix 
{ 
    for (int i = 0; i < matrix->n_rows; i++) 
    //       ^^^^^^ 
    { 
     free(matrix->pp_matrix[i]); 
    } 
    free(matrix->pp_matrix); 
} 
+1

好點,但截圖沒有那麼翔實;行數和列數都是4. – Codor

+0

@Codor我沒有調查截圖,但乍一看似乎矩陣有五列。 –

+0

你是對的;我的錯。 – Codor