2014-10-01 50 views
2

說我有以下設置:釋放返回的變量用C

struct matrix 
{ 
    int row, col; 
}; 

struct matrix* createMatrix(int row, int col) 
{ 
    struct matrix* t_matrix; 
    t_matrix = (struct matrix*) malloc(sizeof(struct matrix)); 
    t_matrix->row = row; 
    t_matrix->col = col; 

    return t_matrix; 
} 

,然後我想有一個暫時返回一個結構矩陣*的功能,但不改變原始矩陣(非常重要):

struct matrix* transpose(struct matrix* mat) 
{ 
    return createMatrix(mat->col, mat->row); 
} 

我該如何釋放這個轉置矩陣,但仍然暫時使用它的值?

編輯:刪除createMatrix

解決了不必要的參數:由於一些建議,我最終作出一個指向我的所有矩陣和釋放他們在結束程序。

+0

注意,你'createMatrix()'不採取'結構矩陣*' – Jack 2014-10-01 02:42:54

+0

你看到使用的'transpose'的返回值'free'什麼問題? – 2014-10-01 02:44:10

+0

我的實際createMatrix功能是與此不同,所以我有點糊塗了:P我固定它雖然。 – m1cky22 2014-10-01 02:51:24

回答

1

通常情況下,你認爲它返回一個新的對象矩陣(即,它不會改變作爲參數傳遞任何矩陣)函數的文檔中告訴我們,這是調用代碼的責任來釋放它的時候它不再被使用。

另一種可能性是在一些地方保存這些新創建的矩陣列表和處置或重新使用它們時的一些標準,你知道,他們不再使用;例如通過使用標記,時間戳等。

+0

我的問題是,我怎麼能釋放矩陣?我無法撥打免費(TRANSPOSE(移調)(矩陣)),因爲這會釋放一個創建一個新的矩陣,所以後來我將有兩個轉置矩陣,一個將被釋放,然後我也會有原來的矩陣。 – m1cky22 2014-10-01 02:53:08

+0

,需要在每個矩陣的值(或者更確切地說,它的地址)存儲在它自己的指針或使用某種類型的集合對象來存儲他們。 – SylvainL 2014-10-01 02:56:05

0

要記住的關鍵是需要有freemalloc。以下是一些示例代碼,說明如何使用這些函數。

// Create a matrix 
struct matrix* m1 = createMatrix(10, 15); 

// Create a transpose of the matrix. 
struct matrix* mt1 = transpose(m1) 

// Create another transpose of the matrix. 
struct matrix* mt2 = transpose(m1) 

// Free the second transposed matrix 
free(mt2); 

// Free the first transposed matrix 
free(mt1); 

// Free the original matrix 
free(m1);