Reputation: 5211
I have integers under the value of 255 and want to save them into an char array. Im experimenting with some tests:
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int
main(void)
{
char string[10];
int integers[10]; //all under 255.
int j;
for(j=0; j<10; j++)
{
integers[j]=j;
}
int i;
for(i=0; i<10; i++)
{
string[i]=(char)integers[i];
}
printf("%s \n", string);
return 0;
}
when I run the debugger to the end of the of the program the string contains the following ascii values:
"\000\001\002\003\004\005\006\a\b\t"
First I dont understand why after the 006 an \a appears and at the end a \t?
Secondly I wonder if there is a better way to do what I am intending? Thanks
Upvotes: 0
Views: 2899
Reputation: 214495
#include <stdio.h>
int main (void)
{
char string[10];
int i;
for(i=0; i<10; i++)
{
string[i] = i;
}
string[9] = '\0';
printf("%s \n", string);
return 0;
}
Upvotes: 1
Reputation: 27549
What you're seeing are escaped representations of ASCII characters 0x06, 0x07, 0x08 and 0x09.
0x06 is ACK
.
0x07 is BEL
or \a
(alert) and simply causes the terminal to go 'ding!'
0x08 is BS
or backspace or \b
.
0x09 is TAB
or \t
.
Upvotes: 6
Reputation: 3046
You don't need to create the first integer array. You can fill directly the string array.
char string[11];
int i;
for(i=0; i<10; i++)
{
string[i] = i;
}
string[i] = '\0';
Upvotes: 0
Reputation: 6854
The ASCII characters you're using 0-9 are non-printable characters.
The printf function is formatting them as \nnn so that they can be seen.
The ASCII character 9 is a tab character, commonly represented as \t
The ASCII character 8 is the backspace character, represented as \b
The ASCII character 7 is a bell "or alarm" character, common represented as \a
See http://web.cs.mun.ca/~michael/c/ascii-table.html
Upvotes: 2