1

So I have an array of integers. I use a for loop to transfer the contents of the int array into the char array. The problem is when I output the values, the decimal %d outputs 0 and 1s but the %c outputs a smiley emotion.

int main()
{
    int array[10] = {0,1,0,1,1,0,1,1,1,0,0};
    char array2[10];
    int i;
    for(i=0;i<10;i++)
    {
        array2[i] = array[i];
        printf("%c %d\n", array2[i],array2[i]);
    }

}
jonn
  • 103
  • 2
  • 2
  • 11

4 Answers4

4

The smiley faces are symbols for "ASCII" characters 1 and 2 in Microsoft codepage 437; and character 0 is invisible; thus your code performs as expected, but maybe not like you intended.

To fill the char array with the ASCII '0' and '1' characters, you can do

array2[i] = '0' + array[i];
2

Try this:

array2[i] = array[i] + '0';

This converts 0 or 1 to '0' or '1'

juhist
  • 4,210
  • 16
  • 33
1

c conversion specifier prints a character. ASCII values (I assume you live in the ASCII world) 0 and 1 are non-printable in ASCII. The ASCII value for '0' and '1' characters are 0x30 and 0x31. The result of printing a non-printable is implementation dependent.

ouah
  • 142,963
  • 15
  • 272
  • 331
0

What do you think ASCII character 0 or 1 should look like? I'm going to guess that on your system it prints as a smiley face because it is normally unprintable.

Maybe print the character as hex instead so you can see the bits are set. eg :

printf("%x", ch & 0xff);

(from solution here : Printing hexadecimal characters in C )

If you want to print characters as ints, you just need to cast them.

printf("%d\n", (int)array2[i]);
Community
  • 1
  • 1
LawfulEvil
  • 2,267
  • 24
  • 46
  • No cast needed `array2[i]` is implicitly converted to `int` here. – ouah Mar 25 '15 at 11:11
  • Just because the compiler thinks it knows what you want doesn't mean you should explicitly tell it that is what you want. Its then also clear the other readers of the code that you intended the cast to happen. – LawfulEvil Mar 25 '15 at 11:13