I think most computer scientists will agree that being able to do matrix algebra with pointers is, essentially, the holy grail of learning pointers in C. I present to you, the following beginnings of my matrix algebra library.
#include <stdlib.h>
#include <stdio.h>
#define M 5
#define N 5
void vprint(int *);
void vfill(int *, int);
void mprint(int **);
void mfill(int **);
int main(int argc, char **argv) {
// first let's make us a vector!
int *vector, i;
vector = (int *)malloc(sizeof(int) * M);
vfill(vector, N);
vprint(vector);
free(vector);
// Now... let's make a vector of vectors!
int **matrix, j;
matrix = (int **)malloc(sizeof(int) * M * N);
for (i=0; i<M; i++) {
matrix[i] = (int *)malloc(sizeof(int) * N);
printf("Malloc()'d %d bytes at address %p for matrix[%d].\n",
sizeof(int) * N,
(void *)matrix[i],
i);
}
mfill(matrix);
mprint(matrix);
// before we can free the outer vector,
// we have to free the inner vectors!
for (i=0; i<M; i++) {
free(m[i]);
}
free(matrix);
return 0;
}
void vprint(int *m) {
int i;
printf("-- --\n");
printf("|");
for (i=0; i<M; i++) {
printf("%3d", m[i]);
}
printf("|\n");
printf("-- --\n");
}
void mprint(int **m) {
int i, j;
printf("-- --\n");
for (i=0; i<M; i++) {
printf("|");
for (j=0; j<N; j++) {
printf("%3d", m[i][j]);
}
printf("|\n");
}
printf("-- --\n");
}
void vfill(int *m, int scalar) {
int i;
for (i=0; i<N; i++) {
m[i] = i * scalar;
printf("Assigning %d to the integer stored at %p\n",
i * scalar,
&m[i]);
}
}
void mfill(int **m) {
int i;
for (i=0; i<M; i++) {
vfill(m[i], i);
}
}
Much happier now that I really know what's going on. I much prefer the subscripting syntax to pointer arithmetic. It's just easier to read... and... sane.
0 comments:
Post a Comment