-6

I've written a procedure, that creates 2 matrices and multiplies them. However I have to divide my code into functions, and I have a problem with declaring a function that will allocate the memory for matrices.

Here's my code:

void matrixMult(){
int **A, **B, **C; //matrices
int rowA, colA, rowB, colB; //rows and columns 
int i, j, k; //for iterations

printf("Number of rows in matrix A: \n");
scanf("%d", &rowA);
printf("Number of columns in matrix A: \n");
scanf("%d", &colA);

printf("Number of rows in matrix B: \n");
scanf("%d", &rowB);
printf("Number of columns in matrix B: \n");
scanf("%d", &colB);

//memory allocation
A = (int**)malloc(rowA * sizeof(int));
B = (int**)malloc(rowB * sizeof(int));
C = (int**)malloc(rowA * sizeof(int));

for (i = 0; i < rowA; i++)
  {
   A[i] = (int*)malloc(colA * sizeof(int));
  }

for (i = 0; i < rowB; i++)
  {
   B[i] = (int*)malloc(colB * sizeof(int));
  }

for (i = 0; i < rowA; i++)
  {
   C[i] = (int*)malloc(colB * sizeof(int));
  } 
/* 
the rest of code
*/
}

What should this function look like?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278

2 Answers2

3

You have two ways of doing it that are both used in practice:

  • Write a function that allocates the matrix and returns the result - your function would have the following signature: int **alloc_matrix(size_t rows, size_t columns)
  • Write a function that takes a pointer to matrix pointer, and returns a status code - the signature would be int alloc_matrix(int*** res, size_t rows, size_t columns)

The value returned from the second function would indicate a success or a failure in allocating the memory.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

The first allocation you have an error. You have to alocate an array of pointers to Ints.

A= (int**)malloc(rowA * sizeof(int*));
B = (int**)malloc(rowB * sizeof(int*));
C = (int**)malloc(rowA * sizeof(int*));

for the function problem

int** alocatingArray(size_t nRows, size_t nCols){
...
}

this function will be used to each array returning the primary pointer to the matrix