0

I am trying to make a function that multiplies 2 matrices into a new one , its almost finished but I am having had a hard time trying to figure out whats wrong with this line

Here's the Code:

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

#define ROWS_1  3
#define ROWS_2  3
#define COLS_1  3
#define COLS_2  2


int* matrixMultiply(int mat1[ROWS_1][COLS_1],int mat2[ROWS_2][COLS_2])
{
    int mul = (ROWS_1)*(COLS_2);
    int* ArrofRows;
    int sum=0,i,j,k;
    ***ArrofRows = (int*)malloc(mul)*sizeof(int);***
    if (COLS_1 != ROWS_2)
    {
        printf("ERROR!! Operation Failed!Exiting...\n");
        exit(0);
    }
    else
    {
        for( i=0 ; i<ROWS_1 ; i++)
        {
            for( j=0 ; j<COLS_2 ; j++)
            {
                for( k=0 ; k<COLS_1 ; k++)
                {
                    sum += (mat1[i][k]*mat2[k][j]);
                }
                ArrofRows[(i*ROWS_1)+j] = sum;
                sum = 0;
            }
        }
    }
}

void main()
{
    int mat1[ROWS_1][COLS_1] = {{2,6,9},{3,5,4},{6,7,8}};
    int mat2[ROWS_2][COLS_2] = {{2,4},{6,1},{4,8}};
    int* NewMat;
    NewMat = matrixMultiply(mat1,mat2);
}
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Itay Zaguri
  • 43
  • 1
  • 7
  • 1
    BTW `matrixMultiply` must return a value(int*) – BLUEPIXY Aug 25 '15 at 22:01
  • 2
    I *strongly* advise against highlighting specific lines in a c-program with `*`s. Use a comment (either `/* comment until */` or `//comment until end of line`. – EOF Aug 25 '15 at 22:08
  • This isn't the cause of the error in question (Sourav Ghosh's answer covers that already), but main must be declared as either `int main(void)` or `int main(int, char**)`. Some compilers accept `void main()`, but they aren't required to. – Ray Aug 25 '15 at 22:12

1 Answers1

4

In your code

 ArrofRows = (int*)malloc(mul)*sizeof(int);

should rather be

ArrofRows = malloc(mul *sizeof(int));

or, for better,

ArrofRows = malloc(mul *sizeof(*ArrofRows));

as, you want to allocate memory for mul number of times of the size given by sizeof(int) or sizeof(*ArrofRows).

Otherwise, as it is currently written, you're trying to multiply a pointer (return value of malloc()), which is invalid.

FWIW, to quote the property of multiplication operator (*), from C11, chapter §6.5.5,

Each of the operands shall have arithmetic type. [..]

and a pointer is not an arithmetic type. Hence the error.

That said, always check for the success of malloc() by checking the returned value against NULL before using the returned pointer.

Also, please see why not to cast the return value of malloc() and family

Finally, I understand that this code might be just a snippet but in that case also, your matrixMultiply() function should be returning a value.

Community
  • 1
  • 1
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261