如何在 C 中递增数组中的元素(整数)?

How does incrementing an element(integer) in array work in C?

int main(){
    int a[5]= {5, 1, 15, 20, 25};
    int i, j, k=1, m;
    i = ++a[1]; // i becomes a[1] + 1 which is 2 but a[1] changes to 2 even though I'm assigning a value to i?
    j = a[1]++; // j becomes a[1]+1 which is 2+1 but stay as 2? 
    m = a[i++]; // because i is 2, shouldn't the output be a[3]? 

    printf("\n%d %d %d", i, j, m);
    return 0;
}

在此代码中,输出结果为 3、2、15。

增量具体是如何工作的? 谢谢。

1.

i = ++a[1]; 

//i becomes a[1] + 1 which is 2 but a[1] changes to 2 even though i am assigning a value to i?

正确,i 成为 a[1] + 1 的值,a[1] 也是如此。 a[1]j 都在表达式后具有 2 的值。


2.

j = a[1]++;

// j becomes a[1]+1 which is 2+1 but stay as 2?

否,j 未达到 a[1] + 1 评估的值。

在这个表达式之后,j里面的值仍然是a[1]或者更好的说法是2,但是a[i]的值会变成3 ] 在表达式之后。

后增量运算符(variable)++与预增量运算符++(variable)相反,仅在相应操作后增加操作数的值:

C: What is the difference between ++i and i++?


3.

m = a[i++]; 

// because i is 2, shouldn't the output be a[3]?

不是,因为就像我上面说的,Postincrement-Operator只是在操作后增加操作数的值,所以m = a[i++];中的i仍然是i,而不是i + 1.

预递增运算符 (++x) 递增值并 returns 新值 。 post 递增运算符 (x++) 递增值,returns 旧值 .

如果将预增量和 post-增量运算符分解为不同的两行,很容易看出会发生什么。

int a[5]= {5, 1, 15, 20, 25};
int i, j, k=1, m;

// i = ++a[1]; becomes:
++a[1];    // a = {5, 2, 15, 20, 25}
i = a[1];  // i = 2

// j = a[1]++; becomes:
j = a[1];  // j = 2
a[1]++;    // a = {5, 3, 15, 20, 25}

// m = a[i++]; becomes:
m = a[i];  // m = a[2] = 15
i++;       // i = 3

所以,最后:

i = 3
j = 2
m = 15

特别是在这种情况下:

m = a[i++];

变量 i 之前的值为 2,因此 post-increment 运算符递增 i (变为 3),但是 returns 2,因此该行等同于:

m = a[i];  // Use old value here
i++;       // Increment after

预增加先增加数值,然后returns增加的数值给你。 Post-increment returns 递增前的值。

第一个语句 最初 设置 i=2, 但第三个语句 i++ 再次递增它。这就是结果中 i=3 的原因。 j=2 因为当时这是 a[1] 的值。 m=15 因为在执行语句时,i=2 这是数组中该元素的 (从零开始) 值。

所写的代码做了很多难以破译的事情……因此出现了这个问题。除非作为练习,否则以这种方式编写代码不是一个好主意。