C Programming Absolute Beginner's Guide (3rd Edition)

(Romina) #1
pName = "Theodore M. Brooks";

Tip

The only reason string assignment works is that C puts all your program’s string
literals into memory somewhere and then replaces them in your program with their
addresses. C is not really putting Theodore M. Brooks into pName because
pName can hold only addresses. C is putting the address of Theodore M.
Brooks into pName.

You now have a way to assign strings new values without using strcpy(). It took a little work to
get here, but aren’t you glad you made it? If so, settle down—there’s just one catch (isn’t there
always?).


Be Careful with Lengths


It’s okay to store string literals in character arrays as just described. The new strings that you assign
with = can be shorter or longer than the previous strings. That’s nice because you might recall that
you can’t store a string in a character array that is longer than the array you reserved initially.


You must be extremely careful, however, not to let the program store strings longer than the first
string you point to with the character pointer. This is a little complex, but keep following along—
because this chapter stays as simple and short as possible. Never set up a character pointer variable
like this:


Click here to view code image


main()
{
char * name = "Tom Roberts";
/* Rest of program follows... */

and then later let the user enter a new string with gets() like this:


Click here to view code image


gets(name); /* Not very safe */

The problem with this statement is that the user might enter a string longer than Tom Roberts, the
first string assigned to the character pointer. Although a character pointer can point to strings of any
length, the gets() function, along with scanf(), strcpy(), and strcat(), doesn’t know that
it’s being sent a character pointer. Because these functions might be sent a character array that can’t
change location, they map the newly created string directly over the location of the string in name. If
a string longer than name is entered, other data areas could be overwritten.


Warning
Free download pdf