5

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?

noMAD
  • 7,744
  • 19
  • 56
  • 94

4 Answers4

8

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.

bdonlan
  • 224,562
  • 31
  • 268
  • 324
  • Well, there is an Array.length function in Java but I do not know how it works. I guess something similar could be implemented in C? – noMAD Dec 16 '11 at 04:09
  • 2
    Array.length in Java works by secretly passing pointers to a structure, which contains a length field and a pointer to the actual array. You can do something like this in C. But it would look like `findElements(struct matrix *input)` not `findElements(int matInput[][])`. – bdonlan Dec 16 '11 at 04:11
5
#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;
}
Jon Lin
  • 142,182
  • 29
  • 220
  • 220
anonymous
  • 51
  • 1
  • 1
1

Incase you want to try in C++

If you are given a matrix in parameters

eg:- int function( vector<vector<int>>& matrix )

Then to find the number of columns, you can write

int columns = matrix[0].size();

And to find the number of rows in the given matrix

int rows = matrix.size();

0

Alternatively you can define a maximum length for rows and columns then use those to iterate over the array.

#define MAX_COLS 15
#define MAX_ROWS 15


int * findElements(int matInput[MAX_ROWS][MAX_COLS]) 
{
      int row, col;
      for(row = 0; row < MAX_ROWS; row++)
      {
         for(col = 0; col < MAX_COLS; col++)
         {
            //do stuff
         }
      }
}

This just defines the size of the array, it doesn't necessarily have to have all of its elements filled

Hunter McMillen
  • 59,865
  • 24
  • 119
  • 170