c - 为什么下面代码中的 printf 语句打印的是一个值而不是垃圾值?

标签 c arrays pointer-arithmetic subscript-operator

int main(){
    int array[] = [10,20,30,40,50] ;
    printf("%d\n",-2[array -2]);
    return 0 ;
}

谁能解释 -2[array-2] 是如何工作的以及为什么在这里使用 [ ]? 这是我作业中的一个问题,它给出了输出“-10”,但我不明白为什么?

最佳答案

从技术上讲,这会调用未定义的行为。引用 C11,章节 §6.5.6

If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined. [....]

所以,(array-2) 是未定义的行为。

但是,大多数编译器会读取索引,并且它可能会取消 +2-2 索引,[2[a] a[2] 相同,与 *(a+2) 相同,因此,2[a-2]*((2)+(a-2))],只考虑剩下的要求值的表达式,也就是*(a) 或者,a[0].

然后,检查 operator precedence

-2[array -2] 实际上与 -(array[0]) 相同。因此,结果是值 array[0],并且 -ved。

关于c - 为什么下面代码中的 printf 语句打印的是一个值而不是垃圾值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54691675/

相关文章:

c - 需要使用指针从一个函数内部的另一个函数读取数组元素的值

c - 反转任意大小的矩阵

c++ - 指针变量名返回的值是多少?

c - C中指针运算加减错

c - 在 C 中进行清理的另一种方法?

C 冒泡排序整数数组 - 输出问题

javascript - JSON stringify 忽略数组中的某些值

java - 有没有办法在从 Java 中的输入流读取时将字节更改为整数?

c - 可视化 printf 中指针指示的内容

C strtok() 未正确标记?