开发者

Why doesn't my C program print the array values? [duplicate]

This question already has answers here: Closed 1开发者_JAVA技巧0 years ago.

Possible Duplicate:

A riddle (in C)

 #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;
 }


Problem is, the TOTAL_ELEMENTS is an unsigned value and on the implementation you're trying this on, it's probably unsigned long int. The comparison will try to promote the integer value of d, -1, to an unsigned long, which will result in something like 0xFFFFFFFFFFFFFFFF and that's greater than 7-2=5 (the result of TOTAL_ELEMENTS-2); therefore, the loop condition is evaluated to false and the body is never executed. If you explicitly cast away unsigned from the right hand side of the comparison operator, it should work just fine:

for(d=-1;d <= (int)(TOTAL_ELEMENTS-2);d++)
     printf("%d\n",array[d+1]);

(By the way, the COUNTOF macro is generally defined as:

#define COUNTOF(x) ((sizeof((x))/sizeof(*(x)))

and is used like COUNTOF(array), rather than defining a macro for each array. This is not the reason you're seeing the problem, however; your macro is being used correctly here. This is completely orthogonal to the issue, and it's just a coding style advice.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜