On May 5, 7:19*pm, mdh <m...@comcast.net> wrote:
> void strcpy( char *s, char *t){
>
> while ( *s++ = *t++);
>
> }
>
> Could someone help me understand the library function, which,
> according to the appendix, returns the target string.
Well firstly, this particular implementation of it does NOT return the
target string.
Let's take a look at that loop:
while (*s++ = *t++);
This is the same as the following:
for (;

/* Eternal loop */
{
*s = *t;
++s;
++t;
if (!*(s-1)) break;
}
It copies the destination to the source, increments both pointers, and
finally checks to see whether the last character copied was the null
character. If so, the loop stops.
> So, in this case, what is passed to the library is an array-the
> original string *and a pointer to the target string? What happens if
> the target pointer has not been allocated space? And, is this
> acceptable ie to pass a pointer instead of an actual char array for
> the target string?
If you have an array as follows:
char arr[16];
then when you write the name of the array on its own, what you have is
a pointer to the first element of the array, e.g.:
char arr[16];
char *p;
p = arr; /* Here we have a pointer to the first element */
(There are three special cases in which this isn't so:
1) When sizeof is applied to the array
2) When the addressof operator is applied to the array
3) ...I can't actually think of it off-hand, but I'm sure I'd know
it if I was presented with it.)
A pointer contains a memory address. When you invoke strcpy, you're
giving it two memory addresses, the address of the destination and the
address of the source. If the either pointer is dodgy, you'll get
undefined behaviour. For a pointer not to be dodgy, it must:
1) Point to memory that belongs to you, that is, memory that you're
allowed to access.
2) Point to a big enough chunk of memory to store what you want it to
store. If you go outside the boundary, you're writing to memory that
doesn't belong to you.