2016-04-29 79 views
0

我必須寫一個函數,該函數應該可以幫助我使用結構分配一個矩陣。我今天開始研究結構。 所以我寫了這個代碼與結構和相對主證明功能:我該如何分配一個帶結構的矩陣?

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

typedef struct { 

    int rows; 
    int cols; 
    float **row_ptrs; 
} Mat; 

Mat* Mat_alloc(int rows, int cols); 

int main(int argc, char **argv) 
{ 
     Mat *m1 = Mat_alloc(int rows, int cols); 

    return 0; 
} 
Mat* Mat_alloc(int rows, int cols) 
{ 
    Mat matrice; 
    matrice.rows = rows; 
    matrice.cols = cols; 
    float** matrice= (float**)malloc((matrice.rows)*sizeof(float*)); 
    for(int i = 0; i < matrice.cols; i++) 
    { 
     matrice[i] = (float*)malloc((matrice.cols)*sizeof(float)); 
    } 
    matrice.row_ptrs = matrice; 
    return matrice; 
} 

我知道我做一些mistakes.Someone能幫我已瞭解我該怎麼辦呢?

+0

首先找到[好初學者的書(http://stackoverflow.com/questions/562303/the -definitive-c-book-guide-and-list)並學習如何調用函數。然後繼續閱讀書籍並瞭解*作用域*以及一旦函數返回時定義的函數會發生什麼。 –

+0

注意:代碼最終需要伴隨'Mat_free(Mat *);' – chux

+0

代碼中沒有矩陣(又稱二維數組),沒有任何可用作一個的矩陣。指針不是數組,反之亦然。 – Olaf

回答

0

chrisd1100給了一個很好的答案,但只有一點點迂腐這是我的:

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

typedef struct { 

    int rows; 
    int cols; 
    float **row_ptrs; 
} Mat; 

Mat* Mat_alloc(int rows, int cols); 

int main(void) 
{ 
    int i; 

    int rows = 10; 
    int cols = 10; 

    Mat *m1 = Mat_alloc(rows, cols); 

    for (i=0; i<cols; i++) 
    { 
     free(m1->row_ptrs[i]); 
    } 
    free(m1->row_ptrs); 
    free(m1); 

    return 0; 
} 

Mat* Mat_alloc(int rows, int cols) 
{ 
    Mat *m1 = malloc(sizeof(Mat)); 
    m1->rows = rows; 
    m1->cols = cols; 
    m1->row_ptrs = malloc((m1->rows)*sizeof(float*)); 
    for(int i = 0; i < m1->rows; i++) 
    { 
     m1->row_ptrs[i] = malloc((m1->cols)*sizeof(float)); 
    } 

    return m1; 
} 
+0

讓我看看我是否真的知道如何釋放它。我不得不這樣做,前兩次釋放,我可以釋放在結構體Mat(float ** row_ptrs)中定義的矩陣,但是之後我也要釋放Mat類型的m1。不是嗎? –

+0

是的。你可以按照相反的順序釋放它們。 – LPs

+0

謝謝你的支持:) –

1

int rowsint cols未初始化進入Mat_alloc。你需要給這些數值!

int main(int argc, char **argv) 
{ 
     int rows = 10; 
     int cols = 10; 
     Mat *m1 = Mat_alloc(rows, cols); 

     //do something 
     //call your Mat_free(m1) function 

    return 0; 
} 

確保您返回指針Mat結構,這個功能太:

Mat* Mat_alloc(int rows, int cols) 
{ 
    Mat *m1 = malloc(sizeof(Mat)); 
    m1->rows = rows; 
    m1->cols = cols; 
    float** matrice= (float**)malloc((m1->rows)*sizeof(float*)); 
    for(int i = 0; i < m1->rows; i++) 
    { 
     matrice[i] = (float*)malloc((m1->cols)*sizeof(float)); 
    } 
    m1->row_ptrs = matrice; 
    return m1; 
} 

此外,請確保您創建一個Mat_free功能free起來Mat_alloc分配的內存。

+0

謝謝您的評論! –

+0

好奇:爲什麼'matrice [i] =(float *)malloc((m1-> cols)* sizeof(float))'中不必要的強制轉換'(float *)'? – chux

+0

@chux頑皮的問題;) – LPs