• C

Char Array and Integer

In following code I don't understand how can I assign integer to char ?

# include<stdio.h>

void main(void)
      char setOne[10];
      char setTwo[10];

      setOne[0] = 65;
      setTwo[0] = 66;

      setOne[1] = '\0';
      setTwo[1] = '\0';

      setOne[0] = (setOne[0] + setTwo[0]) % 128;      



Who is Participating?
Infinity08Connect With a Mentor Commented:
Take a look at the ASCII table. You can find one here for example :


You'll see that the character with ASCII code 3 is the ETX (end of text) character. This is a control character, rather than a printable character (just like the other characters with an ASCII code under 32).

In principle, there is no problem to write that character to a file, however the program that will read the file will have to take that into account - it will not be able to print it.
A char is basically a signed integer value of size one byte (8 bits usually). It can contain all values between -128 and 127.

An assignment like this :

        char c = 65;

is thus entirely valid. But it would have been a lot clearer if this was used instead :

        char c = 'A';

This does exactly the same thing since the ASCII value for the character 'A' is 65.
Char's are one byte integer values.
If your character set is ASCII
'\0'  == 0
'A' == 65
char type is a numerical type, like int or long.
of course it has smaller length and value range.

signed char:
len: 8b
range: -128 -> 127

len: 8b
range: -128 -> 127 or 0 -> 255 (not defined by standard)

unsigned char:
len: 8b
range 0 -> 255

So you can write

char c = 50;

but If you write

char c = 1000;

you will get an warning from compiler.
s_moreAuthor Commented:

What if I assign:

char test  =  3;

and output it to a text file ( I'll get a not readable character ), will this cause any issues
with any other applications trying to read this text file. I've a application that complains
"binary data encountered in text file". I'm not sure why is this considered as a binary data.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.