打印数组元素 [英] Printing array elements
问题描述
下面的C方案的预期输出打印的数组元素。但是,当实际运行,它没有这样做。
The expected output of the following C program is to print the array elements. But when actually run, it doesn't do so.
#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;
}
这是什么原因?
推荐答案
当你做的比较 D&LT; =(TOTAL_ELEMENTS-2)
,一个类型转换执行。 D
的类型为符号int
,而(TOTAL_ELEMENTS-2)
的类型为size_t
,这是一个无符号的类型。 C的规则说,当操作员有一个符号和无符号参数,无符号的参数是大于或等于大小的参数签署的,则签订参数转换为无。
When you do the comparison d <= (TOTAL_ELEMENTS-2)
, a type conversion is performed. d
is of type signed int
while (TOTAL_ELEMENTS-2)
is of type size_t
, which is an unsigned type. The rules of C say that when an operator has a signed and an unsigned argument, and the unsigned argument is of greater or equal size to the signed argument, then the signed argument is converted to unsigned.
即,作为比较结束
(size_t) d <= (TOTAL_ELEMENTS-2)
而因为为size_t
是无符号,(为size_t)-1
是一个非常,非常大的数量,而不是 - 1了。对于32位为size_t
这将是2 32 - 1 = 4,294,967,295
And because size_t
is unsigned, (size_t) -1
is a really, really large number, not -1 any more. For a 32-bit size_t
it would be 232 - 1 = 4,294,967,295.
要解决这个问题,你可以明确地投的右手边符号int:
To fix this, you can explicitly cast the right-hand side to signed int:
d <= (int) (TOTAL_ELEMENTS-2)
或者,更好的,刚刚摆脱怪异负索引和等。
Or, better, just get rid of the weird negative indexing and such.
有关将来参考,打开所有的编译器警告即可。 GCC,例如,会如果打开打印警告 -Wall -Wextra
:
For future reference, turn on all the compiler warnings you can. gcc, for instance, will print a warning if you turn on -Wall -Wextra
:
$ gcc -o arrayprint -Wall -Wextra -ansi arrayprint.c
arrayprint.c: In function ‘main’:
arrayprint.c:11: warning: comparison between signed and unsigned
这篇关于打印数组元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!