给定矩阵,找到行数和列数

我想在不知道任何其他事情的情况下找到矩阵所具有的行数和列数。

例:

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*/ } 

我不能运行循环来查找大小,因为我不知道何时终止,也不知道矩阵是否在创建时被初始化。 还有其他方法吗?

你无法在C中做到这一点。如果没有某种附加信息,只需指向一个指针即可找到数组的大小。

支持查询数组长度的语言通过传递一些附加信息来实现。 在C中你也可以这样做,但你必须明确地做到这一点:

 struct matrix { int rows, cols; int *data; // packed representation, or int **data; }; int *findElements(struct matrix *matInput); 

作为一种稍微高级的方法,您可以将数组数据放在内存中的struct matrix之后; 这减少了所需的指针访问次数,因此速度稍快。 但基本技术保持不变。

 #include 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; } 

或者,您可以为行和列定义最大长度,然后使用它们迭代数组。

 #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 } } } 

这只是定义数组的大小,它不一定要填充所有元素