我想在不知道任何其他事情的情况下找到矩阵的行数和列数。
例子:
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
之后;这减少了所需的指针访问次数,因此速度稍快。但基本技术保持不变。
关于c - 给定一个矩阵,找出行数和列数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8529638/