【问题标题】:implementing a function with matrix - differences用矩阵实现函数 - 差异
【发布时间】:2019-02-03 19:24:52
【问题描述】:

我有以下打印矩阵的函数:

void printMat(int* mat, int size)
{
    int i;
    for (i=0 ; i < size ; i++)
        printf("%d ", mat[i]);
    printf("\n");
}

现在,假设我有一个特定的矩阵,我想通过三种方式将它传递给上面的函数来实现它的打印:

void main()
{
    int mat[2][3] = { {1,2,3}, {4,5,6} };

    printMat((int*)mat, 6);     //first way//
    printMat((int*)mat+1, 6);   //second way//
    printMat(mat+1, 6);         //third way//
}

first方式中,函数实际上是获取矩阵的起始地址。我明白了。

但是,我不明白为什么函数在第一种方式中实际上获取矩阵中 第二个元素的地址,而不是 第二行的地址 在矩阵中(而后者实际上是通过第三种方式实现的)。

【问题讨论】:

    标签: c matrix pointer-arithmetic


    【解决方案1】:

    原因是 C 运算符优先级。演员表强于+

    (int*)mat + 1 is the same as ((int*)mat) + 1
    

    所以 mat 在加 1 之前被强制转换为 int*(因此你增加了一个“指向 int 的指针”)

    这里mat+1 没有强制转换,因此它的行为类似于“行增量”,因为在此表达式中mat 充当“指向3 个整数数组的指针”。

    顺便说一句:请注意,您的代码现在具有未定义的行为。

    【讨论】:

      【解决方案2】:

      这与operator precedence有关。

      (类型)运算符优先于二元加法运算符(+)。 如果您希望 第二种方式第三种方式 相同,请将 mat + 1 括号里是() 第二种方式。

      那么,

      printMat((int*)(mat+1), 6);   //second way//
      

      将等同于:

      printMat(mat+1, 6);         //third way//
      

      【讨论】:

        猜你喜欢
        • 2017-08-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-17
        • 2023-03-13
        • 2021-01-19
        • 2013-07-18
        • 1970-01-01
        相关资源
        最近更新 更多