【问题标题】:What x[i][j] = -i*cols - j ; is exactly doing in C什么 x[i][j] = -i*cols - j ;正是在 C 中做的
【发布时间】:2014-06-14 06:50:20
【问题描述】:

我不明白x[i][j] = -i*cols - j ; 到底在做什么。有人可以解释一下,因为我是初学者。我无法理解指针'*'。抱歉英语不好。

int main(int argc, char *argv[]) { 
    int a[5][5]; 
    readarray(5, 5, a); 
    printarray(3, 5, a); 
    return 0; 
}

void readarray(int rows, int cols, int x[rows][cols]) { 
    int i, j; 

    for (i = 0; i< rows; i++) 
        for (j = 0; j < cols; j++) 
            x[i][j] = -i*cols - j ; 
}

void printarray(int rows, int cols, int x[rows][cols]) { 
    int i, j; 
    for (i = 0; i< rows; i++) { 
        for (j = 0; j < cols; j++) 
            printf("%4d", x[i][j]) ; 
        printf("\n"); 
    } 
}

【问题讨论】:

  • i 被取反,然后乘以 cols,然后从中减去 j。然后将该结果存储在二维数组中,使用 i 和 j 作为索引

标签: c


【解决方案1】:

* 这里是乘法,不是指针。

x[i][j] = -i*cols - j ;

这里发生了几件事:

  1. 否定:-i
  2. 乘法:(-i) * cols
  3. 减法:- j
  4. 赋值:将右边的结果赋值给x[i][j]

如果您想了解使用 * 进行解引用和乘法之间的区别,请查看 this thread

【讨论】:

  • 打败我哈哈+1
【解决方案2】:

这只是填充数组元素的值。

x[i][j] = -i*cols - j ; = x[i][j] = -i*5 - j ;

x[0][0] = 0
x[0][1] = -0*5 - 1 = -1
. . .
x[1][0] = -1*5 - 0 = -5
. . 
x[3][3] = -3*5 - 3 = -18

等等..

【讨论】:

    【解决方案3】:

    我认为只执行了一次乘法运算。没有使用指针。

    i=2;
    j=5;
    cols = 5;
    
    x[2][5] = -2 * 5 - 5
    

    【讨论】:

      猜你喜欢
      • 2020-03-28
      • 1970-01-01
      • 1970-01-01
      • 2021-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-06
      • 1970-01-01
      相关资源
      最近更新 更多