I'm trying to store a series of matrices in a contiguous block of memory, and then retrieve them. Each array will be the same size (n x n).
As far as I understand, what I need to do is:
Allocate and initialize each array that I need to store/retrieve.
Allocate a contiguous block of memory of size
(# arrays) * sizeof (1 array)and assign a pointer,***matrices, to the beginning of the blockCopy each array into the block at
matrices[0],matrices[1], ...Print them by sending
matrices[0],matrices[1], ... to amatrix_printfunction
Now, obviously I am misunderstanding something, because it isn't working. This is the output I get right before it crashes:
Matrix A is 16 bytes.
Matrix B is 16 bytes.
So, we will allocate 32 bytes in row_blocks.
Matrix A:
| 1 1 |
| 2 2 |
Matrix B:
| 2 2 |
|
Here is the code for my test case that I'm trying to get working:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void matrix_print(int dim, int ***matrix);
void matrix_init(int dim, int matrix[dim][dim], int val);
int main(int argc, char *argv[])
{
int dim = 2;
int A[dim][dim], B[dim][dim];
matrix_init(dim, A, 1);
matrix_init(dim, B, 2);
printf("Matrix A is %d bytes.\n", sizeof A);
printf("Matrix B is %d bytes.\n", sizeof B);
int ***matrices = malloc(sizeof A + sizeof B);
printf("So, we will allocate %d bytes in matrices.\n\n",
sizeof A + sizeof B);
memcpy(matrices[0], A, sizeof (A));
memcpy(matrices[1], B, sizeof (B));
printf("Matrix A:\n");
matrix_print(dim, &matrices[0]);
printf("Matrix B:\n");
matrix_print(dim, &matrices[1]);
return 0;
}
void matrix_print(int dim, int ***matrix)
{
for (int i = 0; i < dim; i++) {
printf("|");
for (int j = 0; j < dim; j++) {
printf("%2d ", matrix[i][j]);
}
printf("|\n");
}
}
void matrix_init(int dim, int matrix[dim][dim], int val)
{
for (int i = 0; i < dim; i++) {
for (int j = 0; j < dim; j++) {
matrix[i][j] = val;
}
}
}