【发布时间】:2016-05-06 01:11:06
【问题描述】:
我在使用 unsigned char 作为迭代器时遇到问题。使用以下代码会导致卡在 FOR 循环中。 The output looks like this.
unsigned char i;
char * arr;
int * freq;
arr = (char *)(malloc(256*sizeof(char)));
freq = (int *)(malloc(256*sizeof(int)));
for (i=0; i<=255;i++){
arr[i]=i;
freq[i]=0;
printf("%c",i);
}
我的问题是为什么会这样?是因为使用 unsigned char 作为迭代器吗?
【问题讨论】:
-
因为
unsigned char i不能保存大于 255 的值。i<=255始终为真。 -
不要将
malloc和朋友的结果投射到 C 中!并且sizefo(char)被定义 以产生1。明确写出来是没有用的。 -
此外,使用 char 作为迭代器不太可能更“高效”,您不妨使用整数。不过我可能是错的
-
@aidan.plenert.macdonald:数组上的interator的正确类型是
size_t(无符号)。或者,如果保证值是<= SIZE_MAX,则可以使用unsigned int。 -
@chux:
255是标准要求的最小最大值(!)值。没有任何声明unsigned char不能容纳更大的值。
标签: c for-loop iterator char unsigned