12

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]
5
  • read man atof, man strtod Commented Jan 15, 2013 at 18:14
  • 2
    What do you mean "a char array to a string", a char array is a string. Commented Jan 15, 2013 at 18:14
  • 2
    @Mike If and only if there appears a '\0' within the object. Commented Jan 15, 2013 at 18:16
  • char string[100] should probably be a char string[100][N] Commented Jan 15, 2013 at 18:18
  • I know that '\0' is the terminating character, but I need to save the 10 elements of the whole char array to string. Commented Jan 15, 2013 at 18:18

3 Answers 3

34

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'; 
Sign up to request clarification or add additional context in comments.

1 Comment

Unfortunately I do not have 15 reputation to do so I can Data thumb :)
7

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

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

like so:

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

Then string will be a null terminated C string, as desired.

Comments

4

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.