0

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])
    {
    }
Gaurav Sehgal
  • 7,422
  • 2
  • 18
  • 34
Goun2
  • 417
  • 1
  • 11
  • 22
  • 5
    The size parameter should be the first parameter: `void Matrix_func(int size, int x[size][size])` – mch Sep 16 '17 at 18:45

2 Answers2

1

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
Jonesinator
  • 4,186
  • 2
  • 24
  • 18
0

You can pass it as:

void Matrix_func(int size, int x[][size]){
}
Aashish Kumar
  • 2,771
  • 3
  • 28
  • 43