2016-04-29 81 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