简体   繁体   中英

Why can't char works but int does

char array[]= {1,2,3,4,5,6,7,8,9,1,2,3,6,7};
printf("%c\n", array[5]);

This returns " ". Nothing but when I change the char to int it prints "5". I tot char can accept numbers from -128 to 127?

int array[]= {1,2,3,4,5,6,7,8,9,1,2,3,6,7};
printf("%i\n", array[5]);

When you print the char , C assumes the value stored is supposed to represent ASCII encoded text. Accessing array[5] yields the value 6 , which corresponds the ASCII value ACK . This character is not printable, which is why you see no output.

The character 6 is represented by the ASCII value 54 . To produce this value, use the char literal '6' .

For example, try initializing your array as:

char array[]= {'1','2','3','4','5','6','7','8','9','1','2','3','6','7'};

This will result in the behavior you expect.

Alternatively, you can print the character as a formatted integer by using the flag %i in place of %c in your first snippet.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM