0

I'd like to define a function that can process a matrix in a flexible way. That is, I need a function that can deal with matrices of any size.

My first try was to deal with the matrix as a pointer, in this way:

#include <stdio.h>
#include <stdlib.h>

#define MAX_L 10
#define MAX_C 10

void initializeMatrix(int *matrix, int lines, int columns){
    int i,j,color;
    for(i=0;i<lines;i++){
        for(j=0;j<columns;j++){
            *(matrix+i*columns+j) = rand()%10;
        }
    }
}

void printMatrix(int *matrix, int lines, int columns){
    int i,j,color;
    for(i=0;i<lines;i++){
        for(j=0;j<columns;j++){
            printf("%d\t",*(matrix+i*columns+j));
        }
        printf("\n");
    }
}

int main(){
    int x,y,i,color,count,finish;
    int matrix[MAX_L][MAX_C];

    initializeMatrix(matrix,MAX_L,MAX_C);
    printMatrix(matrix,MAX_L,MAX_C);
    return 0;
}

Is there any problem in working with matrices in this way? Is it a good practive?

2 Answers2

1

Is there any problem in working with matrices in this way? Is it a good practice?

No.

void ...Matrix(int *matrix, int lines, int columns) expects an int *matrix. ...Matrix(matrix,MAX_L,MAX_C); does not convert matrix to a int *.

Save time, enable all warnings as your compiler should have told you this already.

The range of indices in C is [0...SIZE_MAX]. Consider size_t instead of int. Take care that size_t is an unsigned type.

With C99 and many compilers since, code can use a VLA declaration as suggested by @dbush.

// void printMatrix(int *matrix, int lines, int columns){
void printMatrix(size_t lines, size_t columns, const int matrix[lines][columns]) {

Use const when the reference object does not change.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
0

You can make the size of each dimension a variable if you list the size parameters first, then use them in the array dimensions.

void initializeMatrix(int lines, int columns, int matrix[lines][columns]){
dbush
  • 205,898
  • 23
  • 218
  • 273