c - 在 C 中创建动态矩阵的方法?

标签 c matrix dynamic-arrays

这是我所知道的在 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/

相关文章:

c - 如何命名一个好的/有意义的类型?

c - 数组未按应有的方式随机化,且值为负数

r - 矩阵乘法-不合格矩阵的宽松定义

algorithm - 调整二维矩阵大小的基本算法

c++ - 具有动态分配大小和预定大小的简单数组内存分配

c++ - 为什么在此代码中调用析构函数?

delphi - Delphi 动态数组包含哪些簿记数据?

python - C 和 Python 之间共享变量

c - fork+exec 没有 atfork 处理程序

c++ - 将(C 类)指针转换为 C++ 矩阵