Programming in C

(Barry) #1
Pointers and Arrays 271

Execution of the assignment statement inside the loop proceeds as follows.The character
pointed to by fromis retrieved and then fromis incremented to point to the next char-
acter in the source string.The referenced character is then stored inside the location
pointed to by to, and then tois incremented to point to the next location in the desti-
nation string.
Study the preceding assignment statement until you fully understand its operation.
Statements of this type are so commonly used in C programs, it’s important that you
understand it completely before continuing.
The preceding forstatement hardly seems worthwhile because it has no initial
expression and no looping expression. In fact, the logic would be better served when
expressed in the form of a whileloop.This has been done in Program 11.14.This pro-
gram presents your new version of the copyStringfunction.The whileloop uses the
fact that the null character is equal to the value 0 , as is commonly done by experienced
C programmers.


Program 11.14 Revised Version of the copyStringFunction


// Function to copy one string to another. Pointer Ver. 2


#include <stdio.h>


void copyString (char to, char from)
{
while ( from )
to++ = *from++;


*to = '\0';
}


int main (void)
{
void copyString (char to, char from);
char string1[] = "A string to be copied.";
char string2[50];


copyString (string2, string1);
printf ("%s\n", string2);

copyString (string2, "So is this.");
printf ("%s\n", string2);

return 0;
}

Free download pdf