3

这是我知道在 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]);
      }
  }

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

4

3 回答 3

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]);
      }
  }
于 2012-10-05T13:55:21.140 回答
2

从 C99 开始(但不是 C++),您可以使用可变长度数组:

int main()
{    
  int i, j, lines, columns;

  printf("Type the matrix lines:\t");
  scanf("%d", &lines);
  printf("Type the matrix columns:\t");
  scanf("%d", &columns);

  {
    int intMatrix[lines][columns];

    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]);
        }
    }
  }
}

甚至像这样:

void readData (int lines, int columns, int array[lines][columns])
{
  int i, j;

  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", &array[i][j]);
      }
  }
}

int main()
{
  int lines, columns;

  printf("Type the matrix lines:\t");
  scanf("%d", &lines);
  printf("Type the matrix columns:\t");
  scanf("%d", &columns);

  {
    int intMatrix[lines][columns];

    readData (lines, columns, intMatrix);
  }
}

但是,在这两种情况下,数组数据都存储在堆栈中,而不是堆中,因此无法正确存储它,并且您不能将其放入结构或任何 malloc'd 中。

于 2012-10-05T14:22:26.910 回答
0
struct matrix {
    type *mem;
};

struct matrix* matrix_new () {
    struct matrix *M = malloc (sizeof(matrix));
    M->mem = malloc (sizeof (type) * rows * cols);
    return M;
}

使用reallocmemcpymemmovefree修改数组的块。要访问单个元素,请使用类似mem[row*cols+col]mem[rows*col+row]取决于对您具有优先级的内容(或您定义行和列的内容)。

于 2012-10-05T13:56:14.527 回答