Skip to content

Instantly share code, notes, and snippets.

@naveen521kk
Last active April 23, 2022 14:52
Show Gist options
  • Save naveen521kk/530d3504c62d23ec1b58583e7248f661 to your computer and use it in GitHub Desktop.
Save naveen521kk/530d3504c62d23ec1b58583e7248f661 to your computer and use it in GitHub Desktop.
A basic C programs for using 2D arrays and doing matrix operations
#include <stdio.h>
#include <stdlib.h>
int main() {
int row, col;
printf("enter row and col:");
scanf("%d %d", &row, &col);
int **mat;
mat = calloc(row, sizeof(int *));
if (mat == NULL) {
printf("memory error");
return 1;
}
for (int i = 0; i < row; i++) {
mat[i] = calloc(col, sizeof(int));
if (mat[i] == NULL) {
printf("memory error");
return 1;
}
for (int j = 0; j < col; j++) {
printf("matrix elements [%d, %d]:", i, j);
scanf("%d", &mat[i][j]);
}
}
printf("mem alloc done");
for (int i = 0; i < row; i++) {
free(mat[i]);
for (int j = 0; j < col; j++) {
printf("%d ", mat[i][j]);
}
printf("\n");
}
free(mat);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment