问题
There is something wrong with the code below... Could someone explain to me whats the problem and why?
#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;
}
回答1:
The sizeof operator: ...
"The value of the result is implementation-defined, and its type (an unsigned integer type) is size_t, defined in < stddef.h > (and other headers)." - C99 standard.
Conversions: ...
"Otherwise, if the operand that has unsigned integer type has rank greater or equal to the rank of the type of the other operand, then the operand with signed integer type is converted to the type of the operand with unsigned integer type." - C99 standard.
The int d(-1) is converted to (TOTAL_ELEMENTS-2) type which is sizeof return type(an unsigned integer). This is usually done by reinterpreting the bits as an unsigned value => -1 signed integer = 0xFFFFFFFF(if int has 32 bits) unsigned integer.
You are trying to compare 0xFFFFFFFF with 0x5(TOTAL_ELEMENTS-2) which is false.
You should have a warning... signed/unsigned mismatch...
C99 standard
回答2:
Usual arithmetic conversions.
In the <=
expression the int
value -1
is converted to the unsigned type of sizeof
and becomes a huge value and the <=
expression is then false.
Use:
for(d=-1;d <= (int) (TOTAL_ELEMENTS-2);d++)
回答3:
Please find the below changes
#include
#define TOTAL_ELEMENTS (sizeof(array) / sizeof(array[0]))
int array[] = {23,34,12,17,204,99,16};
int main()
{
int d,k;
k=TOTAL_ELEMENTS-2;
for(d=-1;d <=k ;d++)
printf("%d\n",array[d+1]);
return 0;
}
来源:https://stackoverflow.com/questions/16981790/what-causes-the-array-in-the-following-code-not-to-be-printed