To pass a matrix in a function We need to pass its dimensions, but how can I pass a matrix which the user defines its dimensions ?
void Matrix_func(int x[size][size])
{
}
To pass a matrix in a function We need to pass its dimensions, but how can I pass a matrix which the user defines its dimensions ?
void Matrix_func(int x[size][size])
{
}
You will probably want to use dynamic memory allocation for that, in which case you can use a double pointer for the values. Also, instead of passing the size all over the place, you can make a struct
for the matrix. For example:
#include <stdio.h>
#include <stdlib.h>
struct matrix_t {
int width;
int height;
int** values;
};
matrix_t* alloc_matrix(int width, int height) {
int i;
matrix_t* matrix;
matrix = (matrix_t*)malloc(sizeof(matrix_t));
matrix->width = width;
matrix->height = height;
matrix->values = (int**)malloc(sizeof(int*) * height);
for (i = 0; i < height; ++i) {
matrix->values[i] = (int*)malloc(sizeof(int) * width);
}
return matrix;
}
void free_matrix(matrix_t* matrix) {
int i;
for (i = 0; i < matrix->height; ++i) {
free(matrix->values[i]);
}
free(matrix->values);
free(matrix);
}
void matrix_func(matrix_t* x) {
int row;
int col;
for (row = 0; row < x->height; ++row) {
for (col = 0; col < x->width; ++col) {
printf("%d ", x->values[row][col]);
}
printf("\n");
}
}
int main() {
int height;
int width;
matrix_t* matrix;
printf("Enter height: ");
scanf("%d", &height);
printf("Enter width: ");
scanf("%d", &width);
matrix = alloc_matrix(width, height);
matrix_func(matrix);
free_matrix(matrix);
}
Example output:
Enter height: 4
Enter width: 5
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0