I am very new to C. I was trying to write a very basic matrix program for practice.
The way the matrix works is that it is created with a given number of rows and columns, and then it callocs a single one dimensional array with enough slots (rows * cols slots... You get the idea). Then to access a slot, you call a matrix_getcell
on the matrix with the cell and it returns a pointer to the cell.
Here is matrix.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
and here is 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;
}
What I tried to do with this was to initialize EACH separate cell to a successive number, such that when I for-looped over it the second time it would hopefully have outputedd:
(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
But instead, it outputs
(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
I have added (and then removed) code to test whether matric_getcell
was returning incorrect results (it doesn't seem to be). I have changed the datatype, I have tried casting... I don't know what else to try.
Why does it seem to be setting each column to the same number?
You matrix_getcell
method has a bug inside when you calculate the position of the cell.
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]);
}
Another bug is there when you are printing the doubles. You should be using %f
instead of %d
to print doubles.
// v--- "%d" is the problem here
printf("(%d, %d): %.3d\n", r, c, *cur);