Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Given a matrix, find number of rows and columns

Tags:

c

matrix

I want to find the number of rows and columns a matrix has without having knowledge of any other thing.

Example:

int * findElements(int matInput[][]) {
      /*Count blah*/
      /*Now to run a loop till the number of rows*/
      /*I need to know the size of the matrix to run the loop above*/
}

I cannot run a loop to find the size as I don't know when to terminate and also don't know if the matrix was initialized while creation. Is there any other method?

like image 715
noMAD Avatar asked Dec 13 '22 07:12

noMAD


2 Answers

You cannot do this in C. It is quite literally impossible, without some kind of additional information, to find the size of an array given just a pointer to it.

Languages which do support querying array length do this by passing some additional information. In C you could do this as well, but you have to do it explicitly:

struct matrix {
    int rows, cols;
    int *data; // packed representation, or int **data;
};

int *findElements(struct matrix *matInput);

As a slightly more advanced method, you could place the array data right after the struct matrix in memory; this reduces the number of pointer accesses needed and thus is slightly faster. But the basic technique remains the same.

like image 151
bdonlan Avatar answered Dec 28 '22 23:12

bdonlan


#include<stdio.h>

int main()
{
    float a[9][2]={{0,1},{1,1}};
    int row=(sizeof(a)/sizeof(a[0]));
    int col=(sizeof(a)/sizeof(a[0][0]))/row;
    printf("%d\n",row);
    printf("%d\n",col);
    return 0;
}
like image 41
anonymous Avatar answered Dec 28 '22 21:12

anonymous