【问题标题】:Scanning values into a matrix without using [ ] C language不使用 [ ] C 语言将值扫描到矩阵中
【发布时间】:2013-03-16 14:52:08
【问题描述】:

我有问题。我被要求编写一个转置矩阵的程序,而不使用 []...例如,我知道如果它是一个一维数组,我可以说 array[3] 与 *(array+3 )...但是我如何使用矩阵来做到这一点?

这是我的扫描代码:

void scan_matrix(matrix mat1,int number_of_rows, int number_of_columns)
{
    int row_index,column_index;
    for(row_index=0;row_index<number_of_rows;row_index++)
    {
        printf("Enter the values of row %d\n",row_index);
        for(column_index=0;column_index<number_of_columns;column_index++)
            scanf("%d",WHAT GOES HERE?????);
    }
}

【问题讨论】:

  • 这取决于matrix 是什么...
  • 一个二维数组。与行和列。我是新手,如果问题不清楚,请见谅。
  • @OriaGruber 如果你不愿意使用 [] ,那么你必须使用 * 算术

标签: c matrix transpose


【解决方案1】:

如果mat1 是一个简单的指针,那么这应该可以为您完成这项工作:

for(row_index=0;row_index<number_of_rows;row_index++)
    {
        printf("Enter the values of row %d\n",row_index);
        for(column_index=0;column_index<number_of_columns;column_index++)
            scanf("%d", (mat1 + row_index*number_of_columns + column_index));
    }

该程序使用矩阵(二维数组)实际上作为一维数组存储在内存中的事实。

让我们采用一个二维矩阵:

1 2 3
4 5 6

这在内存中存储为:

1 2 3 4 5 6

因此,通过使用将数组元素的逻辑位置与实际位置映射的方法来访问正确的变量。我们只需要找出结果是这样的关系:

Pos = Row*Num_Of_Col + Col

【讨论】:

    【解决方案2】:

    如果 mat 是二维 int 数组,例如:mat[3][3]

    那么 scanf 代码将是:scanf("%d",(*(mat+row_index)+column_index));

    a[3] : *(a+3)
    a[3][3] : (*(a+3)+3)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-17
      • 1970-01-01
      • 2022-01-05
      相关资源
      最近更新 更多