考虑这个C程序
#include <stdio.h>
#define TOTAL_ELEMENTS (sizeof(arr))/sizeof(arr[0])
int arr[] = {23, 34, 12, 17, 204, 99, 16};
int main() {
int d;
printf("%zu\n", TOTAL_ELEMENTS);
for (d = -1; d <= (TOTAL_ELEMENTS - 2); d++) {
printf("%d ", arr[d + 1]);
}
return 0;
}
编译器给出的输出为7
根据我的模拟和推理输出应该是
7.
23 34 12 17 204 99 16
现在,为了找出问题所在,我应用了一些变体
考虑这段代码
#include <stdio.h>
#define TOTAL_ELEMENTS (sizeof(arr))/sizeof(arr[0])
int arr[] = {23, 34, 12, 17, 204, 99, 16};
int main() {
int d;
printf("%zu\n", TOTAL_ELEMENTS);
for (d = -1; d <=(int) ((TOTAL_ELEMENTS) - 2); d++) {
printf("%d ", arr[d + 1]);
}
return 0;
}
请注意,我所做的唯一更改是引入了int类型转换,现在它给出了预期的结果。
现在,据我所知,当我们在C程序中进行比较时,它可以正确地转换为更大的数据类型,所以假设TOTAL_ELEMENT甚至有更大的类型,比如long,那么d应该转换为long,程序应该运行良好,但这并没有发生。我在这里遗漏了哪些要点?