带有(死)简单C程序的Bug

Nik*_*iou 1 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;
}
Run Code Online (Sandbox Code Playgroud)

Sad*_*que 9

你需要施放条件:

d <= (int)(TOTAL_ELEMENTS-2)
Run Code Online (Sandbox Code Playgroud)

sizeof 以无符号格式返回字节数.

在CastAfter Cast 之前.宏本身并不是类型安全的,没有强制转换,两个值都会转换为无符号值,结果为false.

  • 另外,我会将`TOTAL_ELEMENTS(sizeof(array)/ sizeof(array [0]))`更改为`TOTAL_ELEMENTS(x)(sizeof(x)/ sizeof(x [0]))` - 它更干净. (2认同)