我想在不知道任何其他事情的情况下找到矩阵所具有的行数和列数.
例:
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*/
}
Run Code Online (Sandbox Code Playgroud)
我不能运行循环来查找大小,因为我不知道何时终止,也不知道矩阵是否在创建时被初始化.还有其他方法吗?
你无法在C中做到这一点.如果没有某种附加信息,只需指向一个指针即可找到数组的大小.
支持查询数组长度的语言通过传递一些附加信息来实现.在C中你也可以这样做,但你必须明确地这样做:
struct matrix {
int rows, cols;
int *data; // packed representation, or int **data;
};
int *findElements(struct matrix *matInput);
Run Code Online (Sandbox Code Playgroud)
作为一种稍微高级的方法,您可以将数组数据struct matrix放在内存之后; 这减少了所需的指针访问次数,因此速度稍快.但基本技术保持不变.
小智 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;
}
Run Code Online (Sandbox Code Playgroud)