Programming in C

(Barry) #1

266 Chapter 11 Pointers


Pointers to Character Strings


One of the most common applications of using a pointer to an array is as a pointer to a
character string.The reasons are ones of notational convenience and efficiency.To show
how easily pointers to character strings can be used, write a function called copyString
to copy one string into another. If you write this function using normal array indexing
methods, the function might be coded as follows:
void copyString (char to[], char from[])
{
int i;

for ( i = 0; from[i] != '\0'; ++i )
to[i] = from[i];

to[i] = '\0';
}
The forloop is exited before the null character is copied into the toarray, thus explain-
ing the need for the last statement in the function.
If you write copyStringusing pointers, you no longer need the index variable i.A
pointer version is shown in Program 11.13.

Program 11.13 Pointer Version of copyString
#include <stdio.h>

void copyString (char *to, char *from)
{
for ( ; *from != '\0'; ++from, ++to )
*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