First - my code that works:
void main(){
int mat1[5][5]={{1,2,3,4,5},
{6,2,5,5,6},
{1,5,6,6,7},
{4,5,6,7,8},
{5,6,7,8,9}};
int mat2[3][3]={{1,2,3},
{2,3,4},
{3,4,5}};
int mat1size=5,mat2size=3,maxsize=MAX(mat1size,mat2size),*ptr,arraysize=0;
ptr=func(mat1,mat2,maxsize,&arraysize);
.
.
.
}
int* func(int mat1[][5],int mat2[][3],int maxsize,int* arraysize){
int i,j,*ptr=(int*)malloc(sizeof(int)*3);
if(fptr==NULL){
printf("Out of memory!");
return;
}
for(i=0;i<maxsize;i++)
for(j=0;j<maxsize;j++)
if(mat1[i][j]==mat2[i][j]){
if(*arraysize%3==0 && *arraysize!=0)
ptr=(int*)realloc(ptr,sizeof(int)*(*arraysize+3));
ptr[*arraysize]=i;
ptr[*arraysize+1]=j;
ptr[*arraysize+2]=mat1[i][j];
*arraysize+=3;
}
return ptr;
}
Problem is that I declare matrix columns in the function's signature. I'm looking for a more general solution. If you wonder what the function should do is this: It checks every common indices on both matrix. If value is equal - adds the row, column and the value to a new array and returns it.
Use variable-length arrays as function arguments (this is 100% standard C99):
#include <stdio.h>
void print_matrix(size_t w, size_t h, int m[w][h])
{
for (size_t i = 0; i < w; i++) {
for (size_t j = 0; j < h; j++) {
printf("%3d ", m[i][j]);
}
printf("\n");
}
}
int main()
{
int arr[2][3] = {
{ 1, 2, 3 },
{ 4, 5, 6 }
};
print_matrix(2, 3, arr);
return 0;
}