Returning a pointer from a function
Here we provide two equivalent implementations of C's standard
strcpy function,
which copies a string from its source, src, to a new destination,
dest.
The C11 standards state that the strcpy function function must
return a copy of its (original) destination parameter.
In both cases, we are returning a copy of the (original) dest parameter -
that is, we are returning a pointer as the function's value.
We say that "the function's return-type is a pointer".
char *strcpy_array( char dest[], char src[] )
{
int i = 0;
while( src[i] != '\0' ) {
dest[ i ] = src[ i ];
++i;
}
dest[ i ] = '\0';
return dest; // returns original destination parameter
}
|
|
char *strcpy_pointer( char *dest, char *src ) // two pointer parameters
{
char *origdest = dest; // take a copy of the dest parameter
while( *src != '\0' ) {
*dest = *src; // copy one character from src to dest
++src;
++dest;
}
*dest = '\0';
return origdest; // returns copy of original destination parameter
}
|
|
Note:
- in the array version,
the function's return type is a pointer to a char.
This further demonstrates the equivalence between array names (here,
dest) and a pointer to the first element of that array.
- in the pointer version,
we move the dest parameter after we have copied each character,
and thus we must first save and then return a copy of the
parameter's original value.
- if very careful,
we could reduce the whole loop to the statement
while((*dest++ = *src++));
But don't.
CITS2002 Systems Programming, Lecture 11, p11, 26th August 2024.
|