-3

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;
}
user121
  • 305
  • 1
  • 3
  • 9

3 Answers3

1
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';
Sinan Ünür
  • 116,958
  • 15
  • 196
  • 339
  • but I wouldn't know before hand, how many characters to append. – user121 Aug 01 '15 at 10:30
  • Of course you wouldn't which is why you can't use fixed size arrays with strings which you plan to extend. You need to understand `malloc`, `realloc`, `strcat` etc (especially the problems with `strcat`). One step at a time. My response answers your specific question. – Sinan Ünür Aug 01 '15 at 11:21
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;
}
-1
 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";
Ishmeet
  • 1,540
  • 4
  • 17
  • 34