L
lovecreatesbeauty
1. In the following code, is the code (line 11) legal? Is there a
notice in the document to tell callers that the parameter s1 should
receive an array variable, i.e. type char[], but not a variable of char
*? p1 and p2 point to the same things but they must be declared as
different types? Is it nature?
char p1[] = "hello123456";
char *p2 = "world";
strncpy(p1, p2, strlen(p2));
And is the lack of the const keyword in the declaration of the
parameter s1 (line 2) an indication that s1 receives an argument of
array?
2. The temporary variable os1 (line 4) is used only once as the return
value (line 12). Is it better to use os1 instead of s1 throughout the
function except the declaration (line 4). Or just don't introduce the
temporary os1, is it also a good idea? Which style do you prefer?
/*from:
http://cvs.opensolaris.org/source/xref/on/usr/src/common/util/string.c*/
char *
strncpy(char *s1, const char *s2, size_t n) /*line 2*/
{
char *os1 = s1; /*line 4*/
n++;
while (--n != 0 && (*s1++ = *s2++) != '\0')
;
if (n != 0)
while (--n != 0)
*s1++ = '\0'; /*line 11*/
return (os1); /*line 12*/
}
notice in the document to tell callers that the parameter s1 should
receive an array variable, i.e. type char[], but not a variable of char
*? p1 and p2 point to the same things but they must be declared as
different types? Is it nature?
char p1[] = "hello123456";
char *p2 = "world";
strncpy(p1, p2, strlen(p2));
And is the lack of the const keyword in the declaration of the
parameter s1 (line 2) an indication that s1 receives an argument of
array?
2. The temporary variable os1 (line 4) is used only once as the return
value (line 12). Is it better to use os1 instead of s1 throughout the
function except the declaration (line 4). Or just don't introduce the
temporary os1, is it also a good idea? Which style do you prefer?
/*from:
http://cvs.opensolaris.org/source/xref/on/usr/src/common/util/string.c*/
char *
strncpy(char *s1, const char *s2, size_t n) /*line 2*/
{
char *os1 = s1; /*line 4*/
n++;
while (--n != 0 && (*s1++ = *s2++) != '\0')
;
if (n != 0)
while (--n != 0)
*s1++ = '\0'; /*line 11*/
return (os1); /*line 12*/
}