Untitled
unknown
plain_text
a year ago
1.3 kB
3
Indexable
#include <stdlib.h> #include <stdio.h> void print_matrix_pointer(int** matrix, int rows, int columns){ int i, j; for(i = 0; i < rows; i++){ for(j = 0; j < columns; j ++){ printf("%d ", matrix[i][j]); } printf("\n"); } } int main(void) { int **arr_p; int xdim = 4; int ydim = 5; // first allocate array that points to arrays of rows // (notice the data type in sizeof operation) arr_p = (int**)malloc(ydim * sizeof(int *)); if (!arr_p) return -1; // memory allocation failed for (int j = 0; j < ydim; j++) { arr_p[j] = (int*)malloc(xdim * sizeof(int)); if (!arr_p[j]) { // memory allocation failed, release memory // will have to go through previously allocated rows for (int i = 0; i < j; i++) { free(arr_p[i]); } free(arr_p); return -1; } for (int i = 0; i < xdim; i++) { // fill matrix with values, multiplication table arr_p[j][i] = (i+1) * (j+1); } } print_matrix_pointer(arr_p, ydim, xdim); // release the memory for (int j = 0; j < ydim; j++) { free(arr_p[j]); } free(arr_p); return 0; }
Editor is loading...
Leave a Comment