gpt4 book ai didi

C 矩阵结构

转载 作者:行者123 更新时间:2023-12-04 11:39:03 26 4
gpt4 key购买 nike

我正在学习 C 并且很难确定我做错了什么,因为我遇到了段错误。
我正在尝试初始化一个矩阵结构,该结构包含一个指向具有实际数据的二维数组的指针。然后用数组中的数据填充它并打印它。

#include "base.h" 

struct Matrix {
int rows; // number of rows
int cols; // number of columns
double** data; // a pointer to an array of n_rows pointers to rows
};
typedef struct Matrix Matrix;

Matrix* make_matrix(int n_rows, int n_cols) {
struct Matrix matrix;
matrix.rows = n_rows;
matrix.cols = n_cols;
matrix.data = (double**)malloc(sizeof(double*) * n_rows);
for(int x = 0; x < n_rows; x++){
matrix.data[x] = (double*)calloc(n_cols, sizeof(double));
}
struct Matrix *m;
m = &matrix;
return m;
}

Matrix* copy_matrix(double* data, int n_rows, int n_cols) {
struct Matrix *matrix = make_matrix(n_rows, n_cols);
for(int x = 0; x < n_rows; x++) {
for(int y = 0; y < n_cols; y++) {
matrix->data[x][y] = data[x+y];
}
}
return matrix;
}

void print_matrix(Matrix* m) {
for(int x = 0; x < m->rows; x++) {
for(int y = 0; y < m->cols; y++) {
printf("%f", m->data[x][y]);
}
}
}

void matrix_test(void) {

double a[] = {
1, 2, 3,
4, 5, 6,
7, 8, 9 };
Matrix* m1 = copy_matrix(a, 3, 3);
print_matrix(m1);
}

int main(void) {
base_init();
base_set_memory_check(true);
matrix_test();
return 0;
}

另外,除了segmentation fault触发错误还有什么可以改的更好?

最佳答案

欢迎来到 C。这里有两个大问题:

1) 不能返回指向函数局部变量的指针。 (与 make_matrix() 中的错误有关)

2) 没有明显的方法可以在 C 中定义“多维”数组,您可以方便地访问像 data[x][y] 这样的元素。 , 除非您的行大小在编译时已知并固定。 (并且您的矩阵维度在编译时未知。)

让我们分别处理它们。

解决1),你想在make_matrix()中做什么实际上是:

Matrix* make_matrix(int n_rows, int n_cols) {
struct Matrix* pmatrix = malloc(sizeof(struct Matrix));
pmatrix->rows = n_rows;
pmatrix->cols = n_cols;
...
...
return pmatrix;
}

但仅此而已并不能修复该错误。数据需要存储在一个大数组 cols中* rows元素,您需要指定如何定位每个项目而不是 data[x][y] .

所以要解决 2),你的矩阵结构定义应该是
struct Matrix {
int rows; // number of rows
int cols; // number of columns
double* data; // <- note that this is a pointer to one dim array
};

, 和内部 make_matrix()
pmatrix->data = malloc(sizeof(double)*n_rows*n_cols);

就是你现在所需要的。

要复制相同维度和格式的矩阵,
Matrix* copy_matrix(double* data, int n_rows, int n_cols) {
struct Matrix *matrix = make_matrix(n_rows, n_cols);
for(int i = 0; i < n_rows*n_cols; i++)
matrix->data[i] = data[i];
return matrix;
}

(我将这个函数命名为 dup_matrix() 而不是 copy_matrix() 因为它实际上创建了一个新实例)

最后,如果您想访问 [x][y] 处的元素,位置应明确计算为 data[x*cols + y] ,所以 printf()线变成
printf("%f ", m->data[x*(m->cols) + y]);

当然,您需要正确检查 malloc() 的返回值。错误并正确清理。

关于C 矩阵结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41128608/

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