我必须写一个函数,该函数应该可以帮助我使用结构分配一个矩阵。我今天开始研究结构。 所以我写了这个代码与结构和相对主证明功能:我该如何分配一个带结构的矩阵?
#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能帮我已了解我该怎么办呢?
首先找到[好初学者的书(http://stackoverflow.com/questions/562303/the -definitive-c-book-guide-and-list)并学习如何调用函数。然后继续阅读书籍并了解*作用域*以及一旦函数返回时定义的函数会发生什么。 –
注意:代码最终需要伴随'Mat_free(Mat *);' – chux
代码中没有矩阵(又称二维数组),没有任何可用作一个的矩阵。指针不是数组,反之亦然。 – Olaf