2011-12-16 97 views
4

我想查找矩阵所具有的行数和列数,而无需知道任何其他事物。给定一个矩阵,找到行数和列数

例子:

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

我不能运行一个循环来找到大小不知何时结束,也不知是否矩阵,同时创建初始化。 有没有其他方法?

回答

8

你不能在C中这样做。没有某种附加信息,仅仅给出一个指针的数组的大小是完全不可能的。

支持查询数组长度的语言通过传递一些附加信息来完成此操作。在C语言中,你可以做到这一点为好,但你必须这样做明确:

struct matrix { 
    int rows, cols; 
    int *data; // packed representation, or int **data; 
}; 

int *findElements(struct matrix *matInput); 

作为一个稍微更先进的方法,你可以在内存中struct matrix后立即放置阵列中的数据;这减少了所需的指针访问次数,因此速度稍快。但基本技术仍然一样。

+0

嘛,有Java中的Array.length功能,但我不知道知道它是如何工作的。我猜想类似的东西可以在C中实现? – noMAD 2011-12-16 04:09:14

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

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

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