简体   繁体   中英

API to convert character to a string in C

Is there an API to convert a character to a string in C?

I basically have a string and want to insert a character at the end of it. Say,

char str[] = "hello";

I want it to look like "hello1";

I am looking for a convenient API instead of something complicated like

#include <stdio.h>
#include <string.h>

int main(void)
{
 char str[] = "hello";
 int len = strlen(str);

 /*assume this is the character I want to add at the end */
 str[len] = '1';
 str[len+1] =  NULL;


 printf("%s",str);

 return 0;
}
char str[] = "hello";

str is an array of six chars: 'h' , 'e' , 'l' , 'l' , 'l' , 'o' , and '\\0' . When you do str[strlen(str)] = '1' , you overwrite the terminating NUL character (which is distinct from the NULL pointer). When you do str[strlen(str) + 1] = '\\0' , you write past the end of the array.

Even with variable length arrays, you cannot resize an array once it storage has been allocated.

What you can do is allocate extra space for the string as in:

char str[ 7 ] = "hello";
size_t len = strlen(str);
str[ len ] = '1';
str[ len + 1 ] = '\0';

If you look for simple way to do it in C, you can use strcat() function.

#include <stdio.h>
#include <string.h>

int main()
{
    char str1[8] = "hello";
    char str2[2] = "1";

    strcat(str1, str2);
    printf("%s",str1);

    return 0;
}
 int len = strlen(str);

In this line your size is 6 ('h','e','l','l','o','\\0') .

So, after this line it becomes

str[len] = '1';

to

('h','e','l','l','o','1')

and the below line is going out of the array size, so this is not allowed and you cannot resize the array.

 str[len+1] =  NULL;

what you can do is allocate a larger size array initially

char str[7] = "hello";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM