【问题标题】:Given a matrix, find number of rows and columns给定一个矩阵,求行数和列数
【发布时间】:2011-12-16 04:04:43
【问题描述】:

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

例子:

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 matrix


    【解决方案1】:

    你不能在 C 中做到这一点。如果没有一些额外的信息,如果只给一个指向它的指针就很难找到数组的大小。

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

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

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

    【讨论】:

    • 嗯,Java 中有一个 Array.length 函数,但我不知道它是如何工作的。我想类似的东西可以用 C 来实现?
    • Array.length 在 Java 中通过秘密传递指向结构的指针来工作,该结构包含一个长度字段和一个指向实际数组的指针。你可以在 C 中做这样的事情。但它看起来像 findElements(struct matrix *input) 而不是 findElements(int matInput[][])
    【解决方案2】:
    #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;
    }
    

    【讨论】:

      【解决方案3】:

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

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

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

      【讨论】:

        【解决方案4】:

        如果您想在 C++

        中尝试

        如果在参数中给你一个矩阵

        例如:- int function( vector&lt;vector&lt;int&gt;&gt;&amp; matrix )

        然后求列数,可以这样写

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

        求给定矩阵的行数

        int rows = matrix.size();

        【讨论】:

          猜你喜欢
          • 2016-08-01
          • 1970-01-01
          • 2021-04-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-08-01
          • 1970-01-01
          • 2020-04-13
          相关资源
          最近更新 更多