10

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]);
}
6
  • 5
    What does "does not work" mean? Is it the fact that you always get the 'c' back? Well, have a look at your code. Commented Nov 18, 2013 at 15:35
  • You've noticed that you're trying to print the cArray[5] not the 6? Commented Nov 18, 2013 at 15:36
  • 2
    You want to store a digit or an integer? Commented Nov 18, 2013 at 15:36
  • Are you trying to serialize something? en.wikipedia.org/wiki/Serialization Note that %c isn't going to show you your integer value, but the character represented by it. Also note your integers will be limited to 255 max. Commented Nov 18, 2013 at 15:37
  • 1
    @SeçkinSavaşçı:- OP has clearly mentioned in question that he wants to store Integer! Commented Nov 18, 2013 at 15:37

8 Answers 8

19

Let's start with the basics.

For x86 architecture(assuming you use it) a char variable is stored in 1 byte and an int variable is stored in 4 bytes.

It is IMPOSSIBLE to store a random integer value in a char variable unless you have some compression schema and know that some integer values will not occur(no random!) in your program. No exceptions.

In your case, you want to store integers in a char array. There are four options:

1.If you want to store a random integer in this char array, then you should get the pointer to the index that you want to store the integer and cast it to an integer pointer and use it like that.

char mychars[10];
int * intlocation = (int*)(&mychar[5]);
*intlocation = 3632; // stores 3632

Beware that this will write to 4 bytes(4 char locations in your array) starting from the index you have specified. You should always check you are not going out of array.Also you should do the same casting for retrieving the value when needed.

2.If your values are between [0,255] or [-128,127] you can safely store your integers in a char since these ranges can be represented using a byte. Beware that char being signed or unsigned is implementation-dependent. Check this out!

mychars[5] = 54;

3.If your integer is just a digit, you can use the char representation of the digit.

mychars[5] = your_digit + 48; // 48 is the ascii code for '0'

4.If you want to store the string representation of your integer, then you should use itoa() and write each char of the resulting string to your array one by one. In that case, you should always check that you are not going out of array.

Sign up to request clarification or add additional context in comments.

Comments

8
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

Comments

1

Normally, a computer exactly does what you tell it. The instruction DWIM (do what I mean) hasn't been invented yet.

cArray[6] = (char) 0; // WHY DOES THIS NOT WORK???

sets the index position 6, but

printf("%c\n", cArray[5]);

prints the index position 5.

Comments

1

I would like to add on to Seçkin Savaşçı's answer (in which you cast a char* pointer to somewhere in the char array to an int* pointer, allowing you to write an integer to the array by dereferencing the pointer).

You can also use bit-shifting:

#include <stdio.h>

int main() {

    int first_int = 4892; // number larger than 127 (max. value of char)
    int second_int = 99584; // same
    
    // char array to hold two integers:
    char array[8]; // ...assuming an integer size of 4 and char size of 1

    // Now, assuming you are on a little endian system (in which the least
    // significant bytes come first), you can add the two above integers to the
    // array like so:

    array[0] = first_int; // assigns first_int's least significant byte
    array[1] = first_int >> 8; // assigns first_int's 2nd least significant byte
    array[2] = first_int >> 16; // assigns first_int's 2nd most significant byte
    array[3] = first_int >> 24; // assigns first_int's most significant byte

    // repeat for second_int:

    array[4] = second_int;
    array[5] = second_int >> 8;
    array[6] = second_int >> 16;
    array[7] = second_int >> 24;

    // You can now prove that this char array holds the two integers like this:

    printf("First integer: %d\n", *((int *) array));
    printf("Second integer: %d\n", *((int *) (array + 4)));

    return 0;
}

On a big endian system you would first assign the most significant byte, and move on to the least significant bytes.

Comments

0

Replace

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

By

cArray[6] = (char)51;
printf("%c\n", cArray[6]);

Should display '3'

I think you will understand your mistake... 0 as int does not represent the printable character '0', but the NULL termination string

51 as int represent the character '3'

Comments

0

You may use itoa(0,&cArry[6],10).

Comments

0

Use the correctly desired format specifier.

cArray[6] = (char) 0; does store an integer 0 into array element cArray[6]. Its the printf() that is fooling OP into thinking that did not work.

Using %c says OP wants the character that is encoded with a 0. (It usually not visible). Use %d to print the integer value of cArray[6].

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

Comments

0

You can add the ASCII value of 0 to the value you want to store digit into the character array. For example if you want to store 0,1,...,9 into the character array A[10], you may use the following code.

     for(j = 0; j<k; j++)
     {
          A[j] = j + '0';  // Same effect if you use A[j] = j + 0x30
     }

This works only if the integer you want to store is less than 10. Otherwise you will have to extract the digits using modulo operator and store.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.