Are FOR loops with char iterators in C possible? -


i'm having problem using unsigned char iterator. using following code results in being stuck inside loop. the output looks this.

unsigned char i; char * arr; int * freq; arr = (char *)(malloc(256*sizeof(char))); freq = (int *)(malloc(256*sizeof(int))); (i=0; i<=255;i++){     arr[i]=i;     freq[i]=0;     printf("%c",i); } 

my question why happens? due using unsigned char iterator?

i <= 255 

if i of type unsigned char , type 8 bit on platform (which is), expression true , have infinite loop. well-defined behavior, though. unsigned char wrap around , value start @ 0 again once has reached 255.

the solution simple of course: change type of i int.

to avoid such surprises in future, make sure turn on compiler's warnings. if compile bogus loop gcc , pass -wall , -wextra flags, tell me this.

main.c: in function ‘main’: main.c:5:17: warning: comparison true due limited range of data type [-wtype-limits]    (i = 0; <= 255; ++i)                  ^ 

Comments

Popular posts from this blog

Hatching array of circles in AutoCAD using c# -

ios - UITEXTFIELD InputView Uipicker not working in swift -

Python Pig Latin Translator -