简体   繁体   中英

Good Practice to use integer array to store characters in C

I am currently learning to program in C and am referring the book by Kernighan and Ritchie. In order to better grasp arrays especially when inputting characters I have searched the internet and noticed that a lot of solutions use an integer array instead of a character array during input. I know that characters are in a sense integers and have lower precedence, so my question is very simple, are there any major cons to declaring an integer array and using it to store characters? In addition, is it good practice to do this as the title suggests?

No, it would be pretty bad practice, in my opinion, since:

  1. Integers are not characters, in general. That is "an array of integer" doesn't communicate as well to the reader what is going on, as "an array of character" does.
  2. You can't use the standard library's string functions, which is sad since an array of characters can often be treated as a string.
  3. It wastes memory.

It would be interesting if you had posted some code which you feel is representable of doing this. I don't think it happens in K&R.

C has various types that can store integers. (Types don't have precedence - perhaps you meant size.) Sometimes, an integer of one byte is enough to store one character of a specific text (if it's known ahead of time that the text will contain a limited range of characters).

In modern systems and applications, support for more than 256 characters is expected or required, so wider character types are often employed. For these types, there are usually library functions that perform operations comparable to those of the char processing functions.

The int type, however, is not one of these types and is generally not intended to be used like that.

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