gpt4 book ai didi

c - 如何使用结构分配矩阵?

转载 作者:行者123 更新时间:2023-11-30 15:09:00 25 4
gpt4 key购买 nike

我必须编写一个函数来帮助我使用结构体分配矩阵。我今天开始研究结构体。所以我用该结构和相对 main 编写了这段代码来证明该功能:

#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;
}

我知道我犯了一些错误。有人可以帮助我理解我该怎么做吗?

最佳答案

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 函数来释放Mat_alloc 中分配的内存。

关于c - 如何使用结构分配矩阵?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36940600/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com