我对 C 很陌生。我试图编写一个非常基本的矩阵程序来练习。
矩阵的工作方式是,它是用给定数量的行和列创建的,然后它调用一个具有足够槽位的一维数组(行 * 列槽......你明白了)。然后,要访问槽,您可以在带有单元的矩阵上调用 matrix_getcell
,它会返回指向该单元的指针。
这是矩阵.h:
#ifndef MATRIX_H
#define MATRIX_H
#include <stdlib.h>
#include <stdio.h>
typedef unsigned int uint;
typedef struct matrix matrix;
struct matrix {
uint rows;
uint cols;
double *data;
};
matrix *matrix_new(uint rows, uint cols) {
matrix *n = malloc(sizeof(matrix));
if (n == NULL) exit(1);
n->data = calloc(rows * cols, sizeof(*(n->data)));
if (n->data == NULL) exit(1);
n->rows = rows;
n->cols = cols;
return n;
}
void matrix_del(matrix *m) {
if (m == NULL) return;
free(m->data);
free(m);
}
double *matrix_getcell(matrix *m, uint row, uint col) {
if (row >= m->rows) {
fprintf(stderr, "Invalid row: %d\n", row);
exit(1);
}
if (col >= m->cols) {
fprintf(stderr, "Invalid col: %d\n", col);
exit(1);
}
uint pos = (m->rows * row) + col;
return &(m->data[pos]);
}
#endif
这是 main.c:
#include <stdio.h>
#include "matrix.h"
int main(int argc, char **argv) {
matrix *m = matrix_new(3, 3);
/* I know that a 3x3 will have 9 cells, so
* fill them up with successive numbers
*/
for (int i = 0; i < 9; i++) {
m->data[i] = i;
}
/* Now, run through each cell, row by column
* and print out the coords and the contents.
*/
for (uint r = 0; r < 3; r++) {
for (uint c = 0; c < 3; c++) {
double *cur = matrix_getcell(m, r, c);
printf("(%d, %d): %.3d\n", r, c, *cur);
}
}
matrix_del(m);
return 0;
}
我尝试做的是将每个单独的单元格初始化为连续的数字,这样当我第二次对其进行 for 循环时,它有望输出:
(0, 0): 0
(0, 1): 1
(0, 2): 2
(1, 0): 3
(1, 1): 4
(1, 2): 5
(2, 0): 6
(2, 1): 7
(2, 2): 8
但相反,它输出
(0, 0): 0
(0, 1): 0
(0, 2): 0
(1, 0): 1
(1, 1): 1
(1, 2): 1
(2, 0): 2
(2, 1): 2
(2, 2): 2
我添加(然后删除)代码来测试 matric_getcell
是否返回不正确的结果(似乎没有)。我已经更改了数据类型,我已经尝试过转换...我不知道还能尝试什么。
为什么似乎将每一列设置为相同的数字?
最佳答案
当您计算单元格的位置时,matrix_getcell
方法内部存在错误。
double *matrix_getcell(matrix *m, uint row, uint col) {
...
// Should be (m_cols * row) + col.
uint pos = (m->rows * row) + col;
return &(m->data[pos]);
}
打印 double 时存在另一个错误。您应该使用 %f
而不是 %d
来打印 double 。
// v--- "%d" is the problem here
printf("(%d, %d): %.3d\n", r, c, *cur);
关于C 多维数组不接受对其成员的修改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18555292/