-1

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.

Muli Yulzary
  • 2,559
  • 3
  • 21
  • 39

1 Answers1

0

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;
}
  • Wow that was quick! thanks, can only accept answer in 6 minutes so I'll wait a bit :> What does size_t mean? EDIT: tried it, didn't work. "ERROR: A parameter is not allowed" – Muli Yulzary Nov 27 '13 at 23:03
  • @MuliYulzary I repeat, this is C99. You need to compile it with a compiler that supports C99. Not a C++ compiler, but a C compiler. Not a bad, outdated one like Microsoft's MSVC, but a decent C compiler such as gcc or clang. "What does size_t mean?" - you should be able to google that one. –  Nov 27 '13 at 23:56
  • By the way I have to use Visual C++ because thats what my college uses and I need it to compile and run on it. +Kudos for answer, -Kudos for approach. – Muli Yulzary Nov 28 '13 at 00:15