Skip to content

Instantly share code, notes, and snippets.

@OtavioHenrique
Last active July 18, 2018 04:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save OtavioHenrique/3c5a5906816313ccc4b9905b5454a3df to your computer and use it in GitHub Desktop.
Save OtavioHenrique/3c5a5906816313ccc4b9905b5454a3df to your computer and use it in GitHub Desktop.
Matrix of malloc
#include <stdio.h>
#include <stdlib.h>
void populateMatrix(int* matrix[], int width, int height) {
for(size_t i = 0; i < width; i++) {
for(size_t j = 0; j < height; j++) {
matrix[i][j] = i+j;
}
}
}
void printMatrixBottomHeader(int width) {
printf("|");
for(size_t i = 0; i < width; i++) {
printf("---|");
}
printf("\n");
}
void printMatrix(int* matrix[], int width, int height) {
printMatrixBottomHeader(width);
for(size_t i = 0; i < width; i++) {
printf("| ");
for(size_t j = 0; j < height; j++) {
printf("%d | ", matrix[i][j]);
}
printf("\n");
}
printMatrixBottomHeader(width);
}
int** createMatrix(int width, int height) {
int** matrix = malloc(sizeof(int*) * width);
for(size_t i = 0; i < width; i++) {
matrix[i] = malloc(sizeof(int) * height);
}
return matrix;
}
int main() {
int width, height;
printf("Please, enter with your matrix width: ");
scanf("%d", &width);
printf("Please, enter with your matrix height: ");
scanf("%d", &height);
int** matrix = createMatrix(width, height);
populateMatrix(matrix, width, height);
printMatrix(matrix, width, height);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment