Programming in C

(Barry) #1
Pointers and Arrays 267

Program 11.13 Output


A string to be copied.
So is this.


The copyStringfunction defines the two formal parameters toand fromas character
pointers and not as character arrays as was done in the previous version of copyString.
This reflects how these two variables are used by the function.
A forloop is then entered (with no initial conditions) to copy the string pointed to
by frominto the string pointed to by to. Each time through the loop, the fromand to
pointers are each incremented by one.This sets the frompointer pointing to the next
character that is to be copied from the source string and sets the topointer pointing to
the location in the destination string where the next character is to be stored.
When the frompointer points to the null character, the forloop is exited.The func-
tion then places the null character at the end of the destination string.
In the mainroutine, the copyStringfunction is called twice, the first time to copy
the contents of string1into string2, and the second time to copy the contents of the
constant character string "So is this."into string2.


Constant Character Strings and Pointers


The fact that the call


copyString (string2, "So is this.");


works in the previous program implies that when a constant character string is passed as
an argument to a function, what is actually passed is a pointer to that character string.
Not only is this true in this case, but it also can be generalized by saying that whenevera
constant character string is used in C, it is a pointer to that character string that is pro-
duced. So, if textPtris declared to be a character pointer, as in


char *textPtr;


then the statement


textPtr = "A character string.";


assigns to textPtra pointerto the constant character string "A character string."Be
careful to make the distinction here between character pointers and character arrays, as
the type of assignment just shown is notvalid with a character array. So, for example, if
textis defined instead to be an array of chars, with a statement such as


char text[80];


then you could notwrite a statement such as


text = "This is not valid.";


The onlytime that C lets you get away with performing this type of assignment to a
character array is when initializing it, as in


char text[80] = "This is okay.";

Free download pdf