This topic is now archived and is closed to further replies.


Casting integer array to char array

Recommended Posts

Zeke    122
i have an array int iCheckState[10]={0,1,2,3,4,5,6,7,8,9} but i need to cast this to an array of char's to display the same character as the integer (i.e. make the array above become char array[10]={'0','1','2','3','4','5','6','7','8','9'}. It doesnt work if I put array=(char)iCheckState (i assume cos iCheckState is the address of the first element in that array) neither does it work if i use a for loop like so for (a=0;a<10;a++) array[ a ] = iCheckState[ a ]; I have also tried using sprintf(array, %s, (char)iCheckState) and also putting the above sprintf call in a for loop like the one above. I need to do this so that I can then pass array into MessageBox and it will then display the array but im out of ideas. Can anyone help? thanks for your time "People spend too much time thinking about the past, whatever else it is, its gone"-Mel Gibson, Man Without A Face Edited by - Zeke on 11/4/00 4:13:21 AM

Share this post

Link to post
Share on other sites
Quantum    122
loop through and use itoa()
it should do what you want
it converts i integer to a lpha

either that or i think you could manually add 48 to the value

not sure if theres a way to convert the entire array with one function.
hope this helps

Edited by - Quantum on November 4, 2000 5:56:12 AM

Share this post

Link to post
Share on other sites
Quaternion    122
If you have an integer i, and a char c, like this:

int i = 1;
char c = i;

The output will NOT be 1.

When you cast from integer to char, you get the char which it''s ASCII code is i.

But if you do this:

int i = 231;
char c[3];
_itoa(i, &c, 10); //i for the value, c for the char array,
//and 10 for the value base (decimal)

The output will be 231.

Now, by using _itoa, you can convert a whole int array into a cahr array, using a loop.

"In C we had to code our own bugs. In C++ we can inherit them."

Share this post

Link to post
Share on other sites
Heraldin    122
When you say "an array of chars" to display, do you mean a string? There doesn't seem any need to convert your array of ints to display them; I would use something like:

char str[80]={0};
int iCheckState[] = {0,1,2,3,4,5,6,7,8,9};
int arrayLen=sizeof(iCheckState)/sizeof(*iCheckState);

int idx;
for (idx=0; idx < arrayLen; ++idx)
sprintf(str+strlen(str), "%d", iCheckState[idx]);
if (idx < arrayLen-1)
strcat(str, ", ");
// do MessageBox(str), or whatever


Edited by - Heraldin on November 4, 2000 11:45:57 AM

Share this post

Link to post
Share on other sites
try this one...

void main(void)
int iCheckState[10]={0,1,2,3,4,5,6,7,8,9};
char charArray[10];

for( register i = 0; i < 10; i++ )
charArray = iCheckState[i] + ''0'';

You could make it directly inside the for loop without using the
iCheckState array:

for( register i = 0; i < 10; i++ )
charArray[i] = i + ''0'';

André Luiz Silva

Share this post

Link to post
Share on other sites