我有以下代码的问题.第一个for循环打印数组中的所有元素,而第二个for循环不打印任何东西.为什么?
#define TOTAL_ELEMENTS (sizeof(array) / sizeof(array[0]))
int array[] = {23,34,12,17,204,99,16};
int main()
{
int d;
//Working
for(d=0;d < (TOTAL_ELEMENTS);d++)
{
cout << array[d] <<endl;
}
//This does not work. Why does this code fail? Isn't it same as the one above?
//If I assing TOTAL_ELEMENTS to a variable and then use that in for loop (below), it works! Why?
for(d=-1; d < (TOTAL_ELEMENTS);d++)
{
cout << array[d + 1] << endl;
}
}
Run Code Online (Sandbox Code Playgroud)
任何帮助表示赞赏.
sizeof运算符返回一个size_t值,这是一个无符号整数类型,所以在这个循环中:
for(d=-1; d < (TOTAL_ELEMENTS);d++)
Run Code Online (Sandbox Code Playgroud)
-1 被转换为非常大的无符号整数值.