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?
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.
#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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With