I used strncat
several times, but just now check its formal definition in the standard:
#include <string.h>
char *strncat(char * restrict s1,
const char * restrict s2,
size_t n);
The strncat function appends not more than n characters (a null character and characters that follow it are not appended) from the array pointed to by s2 to the end of the string pointed to by s1. The initial character of s2 overwrites the null character at the end of s1. A terminating null character is always appended to the result.
Normally I would think of s1
and s2
simply as pointers to char. But as seen, the standard calls them differently:
s1
s2
The only difference between s1
and s2
is a const qualifier - is that why one is called an array and the other called a string?
Moreover, in the footnote:
Thus, the maximum number of characters that can end up in the array pointed to by s1 is strlen(s1)+n+1.
So here they refer to s1
differently: an array (not a string) pointed by s1
Is there any implication of these different ways of calling s1
and s2
?
The only difference between s1 and s2 is a const qualifier
No, not necessarily.
The destination array, s1
must be already null-terminated. So, it can be safely called a string.
Quoting C11
, chapter §7.1.1/p1, Definitions of terms
A string is a contiguous sequence of characters terminated by and including the first null character. [...]
However, for the source array s2
, null-termination is not a must, in case, given size n
is less than the actual length of the array. So, it must not be a string, always.
So, TL;DR - The destination array will be a string always (hence can be used interchangeably) but there's no such guarantee for the source array.
Also, just to highlight the diference in the usage, let's compare this with the description of strcat()
, which has a similar syntax, minus the size. So, there, both the arguments needs to be null-terminated as there is no other means for the function to determine the end of the source array s2
. Thus, notice the wordings there (emphasis mine), from chapter §7.24.3.1
The
strcat
function appends a copy of the string pointed to bys2
(including the terminating null character) to the end of the string pointed to bys1
. The initial character ofs2
overwrites the null character at the end ofs1
. If copying takes place between objects that overlap, the behavior is undefined.
Here, both the arrays must be strings, and hence, the usage.
In C, a string is NUL
-terminated, where an array is not (necessarily). That's why this function takes the n
parameter; because s2
is not necessarily NUL
-terminated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With