【问题标题】:i need to take size of the matrix from user我需要从用户那里获取矩阵的大小
【发布时间】:2014-04-02 19:45:42
【问题描述】:

我想在 C 中创建一个矩阵,但矩阵的大小必须由用户确定。有我的代码。

int row1,column1;
printf("Please enter number of rows in first matrix: ");
scanf("%d",&row1);
printf("Please enter number of columns in first matrix: ");
scanf("%d",&column1);
int M1[row1][column1];

我在第 1 行和第 1 列出现错误(在最后一行)。从用户那里获取矩阵大小的正确方法是什么?

【问题讨论】:

标签: c matrix rows


【解决方案1】:

这是因为你不能用数组长度作为变量来初始化数组。声明一个指针,使用malloc动态分配数组。

int row1,column1;
printf("Please enter number of rows in first matrix: ");
scanf("%d",&row1);
printf("Please enter number of columns in first matrix: ");
scanf("%d",&column1);

int **arr;

//allocate the memory
arr=malloc(sizeof(int*)*row1);

int i;
for (i=0;i<row1;i++)
  *(arr+i)=malloc(sizeof(int)*column1);


//do what you want to do


//free the memory
for (i=0;i<row1;i++)
  free(*(arr+i));

free(arr);

【讨论】:

    【解决方案2】:

    在 c 中要创建用户定义大小的矩阵,您需要使用 malloc 或 alloca() 进行动态分配。您可以阅读此link 以获取有关在 c 中创建用户定义大小的数组的信息

    【讨论】:

      【解决方案3】:

      相关:dynamic allocating array of arrays in C

      首先分配一个指针数组:

      M1 = (int**)malloc(row1 * sizeof(int*));
      

      然后将每个指向另一个数组。

      for(i = 0; i < row1; i++)
        M1[i] = (int*)malloc(column1 * sizeof(int));
      

      【讨论】:

        【解决方案4】:

        您必须动态分配数组,因为您在编译时不知道大小。

        我的提示:使用单个数组更简单:

        int M1[] = new int[row1 * column1];
        

        然后把它写成

        M1[column + line * row1];
        

        如果你绝对需要二维矩阵,请参考这个问题:How do I declare a 2d array in C++ using new?

        并且不要忘记正确地删除[]您的数组。

        【讨论】:

          猜你喜欢
          • 2018-04-19
          • 2019-11-21
          • 1970-01-01
          • 2023-02-04
          • 1970-01-01
          • 2012-08-21
          • 1970-01-01
          • 1970-01-01
          • 2013-11-23
          相关资源
          最近更新 更多