Nicky Mirfallah
Nicky Mirfallah

Reputation: 1054

Store an integer in char array in C

Running the code below prints b = and i = 15.

int i = 15;
char b = (char) i;
printf("b = %c and i = %d\n", b, i);

How can I store this integer in the character? At the end I'm trying to have a char array of size 1024 which has i (15) as the first character and rest 0.

update: I tried :

int i = 15;
char buffer[1024];
snprintf(buffer, 10, "%d", i);
printf("buffer[0] = %c, buffer[1] = %c\n", buffer[0], buffer[1]);

And the result printed was:

buffer[0] = 1 , buffer[1] = 5

Upvotes: 2

Views: 24306

Answers (5)

anonymoose
anonymoose

Reputation: 868

You did store the integer in the character, it's just that %c converts a character to its ASCII value. All ASCII values below 31 are non-printable.

If you run

printf("b = %d and i = %d\n", (int)b, i);

it will print 15.

If you want a representation of i as a string:

char buf[12]; //Maximum number of digits in i, plus one for the terminating null
snprintf(buf, 12, "%d", i);

This will store a string representation of i in buf.

Upvotes: 4

Nguai al
Nguai al

Reputation: 958

Clarification:

The range of char is -128..127. The range of unsigned char is 0..255.

If capturing ASCII values is the goal, declaring buffer variable to unsigned char type seems to be more appropriate.

Upvotes: 1

Sourav Ghosh
Sourav Ghosh

Reputation: 134286

The problem here is, variable b already has a value 15 but since this does not constitute to a printable ASCII, using %c format specifier, you won't be able to see any output.

To print the value, use %hhd format specifier.

At the end I'm trying to have a char array of size 1024 which has i (15) as the first character and rest 0.

Well, you can define an array and assign values accordingly. Something like

#define SIZE 1024

char arr [SIZE] = {0}; //initialization, fill all with 0
arr[0] = 15;           //first value is 15

should do the job.

Upvotes: 1

Neer Patel
Neer Patel

Reputation: 441

You can't store Integer datatype in Character datatype(datatype conflict). But what you are want, can be achieved by taking 2-dimensional character array.

char b[1024][1024];
itoa(i,b[0],20); /// 
for(int i = 1 ; i < 1024 ; i++)
    itoa(0,b[i],20);

Function itoa converts integer into character array and stores it into the character array. Hope it helps.

click here for more info :)

Upvotes: 0

Kellei
Kellei

Reputation: 61

A char is an 8-bit unsigned value (0 - 255) and it does indeed store 15 in it, the problem is, that in ASCII table 15 means "shift in" non-printable character, and %c interprets the value as an ascii character.

char b = (char) i;
printf("b = %d and i = %d\n", b, i);

to get

b = 15 and i = 15

if you used i = 90 in your current code, this would be printed:

b = Z and i = 90

Upvotes: 1

Related Questions