Advertisement
Advertisement


Convert char array to string use C


Question

I need to convert a char array to string. Something like this:

char array[20];
char string[100];

array[0]='1';
array[1]='7';
array[2]='8';
array[3]='.';
array[4]='9';
...

I would like to get something like that:

char string[0]= array // where it was stored 178.9 ....in position [0]
2013/01/16
1
10
1/16/2013 3:00:23 AM

Accepted Answer

You're saying you have this:

char array[20]; char string[100];
array[0]='1'; 
array[1]='7'; 
array[2]='8'; 
array[3]='.'; 
array[4]='9';

And you'd like to have this:

string[0]= "178.9"; // where it was stored 178.9 ....in position [0]

You can't have that. A char holds 1 character. That's it. A "string" in C is an array of characters followed by a sentinel character (NULL terminator).

Now if you want to copy the first x characters out of array to string you can do that with memcpy():

memcpy(string, array, x);
string[x] = '\0'; 
2013/01/15
29
1/15/2013 6:24:56 PM


You can use strcpy but remember to end the array with '\0'

char array[20]; char string[100];

array[0]='1'; array[1]='7'; array[2]='8'; array[3]='.'; array[4]='9'; array[5]='\0';
strcpy(string, array);
printf("%s\n", string);
2013/01/15