1 2 3 4 5 6 7 8 9

Let us examine four ways to copy null-terminated strings:

s(for source) is a pointer to a string, t(for target) is a pointer to a sequence of bytes in memory, which is at least as long as 1+strlen(s).

/* Array version */
void Astrcopy ( char s[], char t[] ) {
int i = 0;
while ( (t[i] = s[i]) != '\0' )
i++;
}

/* Pointer version 1 */
void P1strcopy ( char* s, char* t ) {
int i = 0;
while ((*(t+i) = *(s+i)) != '\0')
i++;
}

/* Pointer version 2 */
void P2strcopy ( char* s, char* t ) {
while ((*t++ = *s++) != '\0')
;
}

/* Pointer version 3 */
void P3strcopy ( char* s, char* t ) {
while (*t++ = *s++)
;
}

4 February, 1998

1

Copyright University of Alberta