I think there are a couple of problems with your code.
You can simplify this line:
matrix = malloc(row_pointer_bytes + nrows * single_row_elements_bytes);
to:
matrix = malloc(row_pointer_bytes);
Which allocates space for uint8_t*
many rows in the matrix.
The malloc()
function only requires size_t
amount of bytes needed to allocate requested memory on the heap, and returns a pointer to it.
and that can simply be allocated by knowing how many rows are needed in the matrix, in this case nrows
.
Additionally, your for loop:
for(i = 0; i < nrows; i++)
matrix[i] = matrix[nrows + i * single_row_elements_bytes];
Doesn't allocate memory for matrix[i]
, since each row has n
columns, and you need to allocate memory for those columns.
This should instead be:
for(i = 0; i < nrows; i++)
matrix[i] = malloc(single_row_elements_bytes);
Another issue is how are allocating single_row_elements_bytes
. Instead of:
size_t single_row_elements_bytes = ncols * sizeof **matrix; //**matrix is uint8_t**
This needs allocate uint8_t
bytes for n
columns, not uint8_t**
bytes. It can be this instead:
size_t single_row_elements_bytes = ncols * sizeof(uint8_t);
Having said this, your code will compile if written like this. This is an example I wrote to test the code.
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <inttypes.h>
uint8_t **NewMatrix(unsigned nrows, unsigned ncols);
int
main(int argc, char *argv[]) {
uint8_t **returnmatrix;
unsigned nrows = 2, ncols = 2;
int i, j;
returnmatrix = NewMatrix(nrows, ncols);
for (i = 0; i < nrows; i++) {
for (j = 0; j < ncols; j++) {
printf("Enter number for row %d column %d: ", i+1, j+1);
/* format speficier for uint8_t, from <inttypes.h> */
if (scanf("%"SCNu8"", &returnmatrix[i][j]) != 1) {
printf("Invalid 8 bit number.\n");
exit(EXIT_FAILURE);
}
}
}
printf("\nYour matrix:\n");
for (i = 0; i < nrows; i++) {
for (j = 0; j < ncols; j++) {
printf("%d ", returnmatrix[i][j]);
}
printf("\n");
}
/* Good to free at the end */
free(returnmatrix);
return 0;
}
uint8_t
**NewMatrix(unsigned nrows, unsigned ncols) {
int i;
uint8_t **matrix;
size_t row_pointer_bytes = nrows * sizeof * matrix;
size_t column_row_elements_bytes = ncols * sizeof(uint8_t);
matrix = malloc(row_pointer_bytes);
/* Good to check return value */
if (!matrix) {
printf("Cannot allocate memory for %d rows.\n", nrows);
exit(EXIT_FAILURE);
}
for(i = 0; i < nrows; i++) {
matrix[i] = malloc(column_row_elements_bytes);
if (!matrix[i]) {
printf("Cannot allocate memory for %d columns.\n", ncols);
exit(EXIT_FAILURE);
}
}
return matrix;
}
Input:
Enter number for row 1 column 1: 1
Enter number for row 1 column 2: 2
Enter number for row 2 column 1: 3
Enter number for row 2 column 2: 4
Output:
Your matrix:
1 2
3 4
Compiled with:
gcc -Wall -o matrix matrix.c