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

tem*_*mpy 3 c matrix dynamic-arrays

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

  • 创建指向指针数组的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]);
      }
  }
Run Code Online (Sandbox Code Playgroud)

还有其他方法吗?

Raj*_*Raj 5

你可以这样试试

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]);
      }
  }
Run Code Online (Sandbox Code Playgroud)