那我在下面的程序丢失? [英] What am I missing in the following program?
问题描述
#include<stdio.h>
#define TOTAL_ELEMENTS (sizeof(array) / sizeof(array[0]))
int array[] = {23, 34, 12, 17, 204, 99, 16};
int main() {
int d;
for (d = -1; d <= (TOTAL_ELEMENTS - 2); d++)
printf("%d\n", array[d + 1]);
return 0;
}
为什么for循环一次也没有跑?
Why is the for loop not run even once?
推荐答案
的问题是,的sizeof()
收益为size_t
这是无符号的。 的比较-1
与 TOTAL_ELEMENTS - 2
应导致表示你的警告已经比较无符号有符号。当这种情况发生的比较中, 1
被转换为无符号值,该值 MAX_UINT
。在32位平台上,无论是 1
和 MAX_UINT
是 0xFFFFFFFF的
。
The issue is that sizeof()
returns size_t
which is unsigned. Comparison of -1
with TOTAL_ELEMENTS - 2
should result in a warning indicating you have compared unsigned with signed. When this comparison happens, the -1
is converted to an unsigned value which is MAX_UINT
. On a 32-bit platform, both -1
and MAX_UINT
are 0xFFFFFFFF
.
您 TOTAL_ELEMENTS()
宏可以纳入强制转换为(INT)
但是这不是技术上是正确的,因为为size_t
有一个较大的值范围比 INT
。最好改变你的循环变量,使其声明为为size_t
而不是变成负的。
Your TOTAL_ELEMENTS()
macro could incorporate a cast to (int)
but that isn't technically correct because size_t
has a larger value range than int
. Best to change your loop variable so that it is declare as size_t
and never becomes negative.
这篇关于那我在下面的程序丢失?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!