Store an integer in a char array

arrays, c

Solution

cArray[6] = (char) 0; // WHY DOES THIS NOT WORK???
printf("%c\n", cArray[6]);

This code attempts to print a character with the encoding `0`; assuming ASCII, nothing will get displayed because there is no printable character associated with that code.

If you intend to store the ASCII code for the character `'0'` and print it, then you need to write

cArray[6] = 48;               // same as writing cArray[6] = '0' (ASCII)
printf( "%c\n", cArray[6] );

This will print `0` to your console.

If, on the other hand, you want to store any arbitrary integer value1 to `cArray[6]` and display that value, then you need to use the `%d` conversion specifier:

cArray[6];
printf( "%d\n", cArray[6] );

1. That is, any integer that fits into the range of `char`, anyway

Problem

I am trying to store an integer in a `char` array. How can I do that? This is my approach (by casting it the `int` to a `char`) but it does not work. What am I missing? ``` #include <stdio.h> int main(int argc, char** argv) { char cArray[10] = {}; // Store a character in the char array cArray[5] = 'c'; printf("%c\n", cArray[5]); // Store an integer in the char array cArray[6] = (char) 0; // WHY DOES THIS NOT WORK??? printf("%c\n", cArray[6]); } ```

Original source

Related problems