-7
char hi[10] = "bye";
char a = 'a';
strcat(hi, a);

Like the example above. How would I do this in C? Is there a more general string I cant let hi be?

2 Answers2

3

a is a char type while strcat expects it's both arguments of type char *. To append the char to an array of characters you can do this

int index = strlen(hi);
if(index < sizeof(hi)-1)
    hi[index] = a;

Note that in this particular case the initializer will initialize the first three elements of hi to b, y and e respectively. The rest of the elements will be initialized to 0. Therefore you do not need to take care of the null termination of the array after appending each character to it. But in general you have to take care of that.

int index = strlen(hi);
if(index < sizeof(hi)-1){
    hi[index] = a;
    hi[index+1] = '\0';
}
haccks
  • 104,019
  • 25
  • 176
  • 264
  • 6
    And in general, one then needs to add `hi[index+1] = '\0';` — though in the question's context, where the array has been initialized with trailing zeros, it is not actually crucial. – Jonathan Leffler Feb 02 '18 at 06:49
  • @JonathanLeffler; Yes agreed but as you pointed out it is not necessary in this particular case. – haccks Feb 02 '18 at 06:52
1
strcat(hi, (char[]){a,0});

This would append the a.

Or you can do this

char s[]={a,0};
strcat(hi,s);

Or simply

   #define MAXLEN 10
   ...
   size_t len = strlen(hi);
   if( len+1 <= MAXLEN-1)
      hi[len]=a,hi[len+1]=0;
   else
     // throw error. 

In your case hi[len+1]=0 is not required as it is already filled with \0. Also as mentioned by Serge that you can use simply used the string literal as the second parameter to the strcat function.

strcat(hi,"a");

There is a subtle difference in this two as mentioned by Serge again, that string literals are const but the compound literals are not.

user2736738
  • 30,591
  • 5
  • 42
  • 56