这是我知道的在 C 中动态创建矩阵(二维数组)并将用户输入读取到其元素中的唯一方法:

  • 创建一个指向 x 指针数组的指针,其中每个指针
    表示矩阵中的一行 - x 是矩阵中的行数(其高度)。
  • 将此数组中的每个指针指向具有 y 元素的数组,
    其中 y 是矩阵中的列数(宽度)。

  • int main()
    {
    
      int i, j, lines, columns, **intMatrix;
    
      printf("Type the matrix lines:\t");
      scanf("%d", &lines);
      printf("Type the matrix columns:\t");
      scanf("%d", &columns);
    
      intMatrix = (int **)malloc(lines * sizeof(int *));
      //pointer to an array of [lines] pointers
    
      for (i = 0; i < lines; ++i)
          intMatrix[i] = (int *)malloc(columns * sizeof(int));
          //pointer to a single array with [columns] integers
    
      for (i = 0; i < lines; ++i)
      {
          for (j = 0; j < columns; ++j)
          {
            printf("Type a number for <line: %d, column: %d>\t", i+1, j+1);
            scanf("%d", &intMatrix[i][j]);
          }
      }
    

    还有其他方法可以做到这一点吗?

    最佳答案

    你可以这样试试

    int main()
    {
      int i, j, lines, columns, *intMatrix;
    
      printf("Type the matrix lines:\t");
      scanf("%d", &lines);
      printf("Type the matrix columns:\t");
      scanf("%d", &columns);
    
      intMatrix = (int *)malloc(lines * columns * sizeof(int));
    
      for (i = 0; i < lines; ++i)
      {
          for (j = 0; j < columns; ++j)
          {
            printf("Type a number for <line: %d, column: %d>\t", i+1, j+1);
            scanf("%d", &intMatrix[i*lines + j]);
          }
      }
    

    关于c - 在C中创建动态矩阵的方法?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12747731/

    10-12 15:01
    查看更多