Skip to content

Instantly share code, notes, and snippets.

@J16N
Created July 24, 2021 14:07
Show Gist options
  • Save J16N/24ba908bb28f79c574fea1c97aabf8cd to your computer and use it in GitHub Desktop.
Save J16N/24ba908bb28f79c574fea1c97aabf8cd to your computer and use it in GitHub Desktop.
Get user defined 2D matrix without predefining rows and columns.
// Required headers
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
// prototypes
int **get_matrix(char *, int *, int *);
void free_matrix(int **, int);
int main(int argc, char *argv[])
{
// Basic usage
int rows = 0, cols = 0;
int **matrix = get_matrix(
"Enter the matrix. Hit CTRL+D to exit.\n"
"Rows start at every newline.\n"
"Columns are seperated by a space.\n",
&rows, &cols
);
// Now you can perform all the matrix operations
// like a 2D array. You can also pass this to a function.
// For example:
// Display all the elements in the matrix
for (int i = 0; i < rows; ++i)
{
for (int j = 0; j < cols; ++j)
printf("%d", matrix[i][j]);
printf("\n");
}
// After you have completed all your matrix
// opertions, make sure to free all the
// allocated memory.
free_matrix(matrix, rows);
return 0;
}
int **get_matrix(char *label, int *row, int *col)
{
// Display label
printf("%s", label);
int **matrix = NULL;
for (int c; (c = getc(stdin)) != EOF; ++(*row))
{
ungetc(c, stdin);
matrix = realloc(matrix, (*row + 1) * sizeof(int *));
*col = 0;
// Loop through all the lines (rows)
for (; (c = getc(stdin)) != '\n' && c != EOF; ++(*col))
{
ungetc(c, stdin);
matrix[*row] = realloc(matrix[*row], (*col + 1) * sizeof(int));
int pos = 0;
// Loop through all the digits of the number and add them
// to the matrix at i-th row and j-th column
while ((c = getc(stdin)) != ' ' && c != '\n' && c != EOF)
{
if (c >= '0' && c <= '9')
{
matrix[*row][*col] = pow(10, pos) * matrix[*row][*col] + (c - '0');
++pos;
}
}
// Return the accidentally read
// newline character to STDIN
if (c == '\n') ungetc(c, stdin);
}
}
return matrix;
}
void free_matrix(int **matrix, int row)
{
// Loop through all the pointers and free them
for (int i = 0; i < row; ++i)
free(matrix[i]);
free(matrix);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment