I have read the documentation of strcat() C library function on a few websites.
I have also read here: Does strcat() overwrite or move the null?
However, one question is still left - can strcat() function be used to override the characters in the destionation string (assume that dest string has enough space for the source string, so there will be no errors)?
I ran the following code and found that it doesn't have the ability to override the dest string's characters...
char dest[20] = "Hello World";
char src[] = "char";
strcat(dest 1, src);
printf("dest: %s", dest);
Assume that the goal is to have a destination string that contains: "Hchar World!"
(I know that strcat() also copies the NULL characters('\0') to the dest string, so if printf() function is called, it should print Hchar, as I mistakenly thought would happen...).
Is that a possible task to do with strcat()? If not, is strcpy() the answer to the question?
If there is an assignment of '\0' (NULL character) in the middle of the string, for example, will strcat() always treat the first '\0' (NULL character) it meets? I mean, If I had:
char str[] = "Hello";
str[2]= 0;
strcat(str, "ab");
I just want to be sure and clarify the misunderstanding. I will be glad to read explanations.
CodePudding user response:
As noted in the comments, the strcat
function will always (attempt to) append the string given as its second argument (traditionally called src
) to that given as its first (dest
); it will produce undefined behaviour if either string is not null-terminated or if the destination buffer is not large enough.
The cppreference site gives better documentation (for both C and C ) than the website you linked. From that site's strcat
page:
(1) … The character
src[0]
replaces the null terminator at the end ofdest
. The resulting byte string is null-terminated.
And:
Notes
Because
strcat
needs to seek to the end ofdest
on each call, it is inefficient to concatenate many strings into one usingstrcat
.
So, in the code you show, calling strcat(dest 1, src);
has the same effect as calling strcat(dest, src);
. However, calling strcpy(dest 1, src);
will produce the result you want (printing Hchar
).
CodePudding user response:
strcat
will write src
string at the end of dst
.
If you want to override dst
with strcat, you first need to make dst
"end" where you want to override it.
Take a look at this code sample:
#include <stdio.h>
#include <string.h>
int main()
{
char dst[20] = "Hello world";
char src[] = "char";
dst[1] = '\0';
strcat(dst, src);
printf("%s\n", dst);
return (0);
}
However, this is not the aim of strcat
, and as said in the comments, the use of strcpy
would be more appropriate here.
#include <stdio.h>
#include <string.h>
int main()
{
char dst[20] = "Hello world";
char src[] = "char";
strcpy(dst 1, src);
printf("%s\n", dst);
return (0);
}