Convert char array to string using C

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

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 this:

 char string[0]= array // where it was stored 178.9 ....in position [0] 
+7
source share
3 answers

You say that 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 would like to have this:

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

You cannot do this. A char has 1 character. 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 from array to string , you can do this with memcpy() :

 memcpy(string, array, x); string[x] = '\0'; 
+23
source

Assuming array is a character array that does not end with \0 , you will want to use strncpy :

 char * strncpy(char * destination, const char * source, size_t num); 

So:

 strncpy(string, array, 20); string[20] = '\0' 

Then string will be C.'s null terminated string, if you like.

+6
source

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); 
+3
source

All Articles