What I have:
char cmd[50] = "some text here";
char v[] = {'a','s','d','c','b'};
So I want to concatenate cmd by adding a letter from v.
Obviously:
strcat(cmd, v[3]);
doesn’t work because strcat doesn’t accept the v[n] parameter n = int.
Problems with your approach.
C strings must end in 0 byte, in other words
'\0'character. Using""adds that automatically, but otherwise you have to add it yourself, and all string functions depend on that 0 being there.Your v array contains characters, not strings, and
strcattakes strings.One solution:
This turns your char array into array of pointers to C strings.
Also, it’s your responsibility to take care that,
cmd[]contains enough space to hold whatever you add to it with strcat (here it does). It’s usually best to usesnprintfto do string concatenation, as it takes total size of the target array including terminating null, and adds that null there always, so it’s harder to mess up. Example with your original char array:Notes: sizeof like this works only when
bufreally is an array, declared with[]like here. Also with snprintf, using same buffer both as destination and format argument may yield unexpected results, so I added a new destination buffer variable.One more snprintf example, with your original two arrays only, appending to end of current contents of cmd:
So clearly, in this particular case, the
strncat(cmd, &v[3], 1)suggested in other answers to add 1 character is much nicer, but benefit of snprintf is, you can add all datatype supported by printf, not chars.