We help IT Professionals succeed at work.

Char Array and Integer

s_more
s_more asked
on
568 Views
Last Modified: 2010-05-18
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;      

      printf("%s\n",setOne);

      getchar();

}
Comment
Watch Question

CERTIFIED EXPERT
Top Expert 2009

Commented:
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.
ozo
CERTIFIED EXPERT
Most Valuable Expert 2014
Top Expert 2015

Commented:
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

char:
=====
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.

Author

Commented:
Infinity08,

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.

slm
CERTIFIED EXPERT
Top Expert 2009
Commented:
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a sample view!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.