Defining Strings Within a Program

I l @ ve RuBoard

Defining Strings Within a Program

As you probably noticed when you read Listing 11.1, there are many ways to define a string. Here are the principal ways: using string constants, using char arrays, using char pointers, and using arrays of character strings. A program should make sure there is a place to store a string, and we will cover that topic, too.

Character String Constants

A string constant is anything enclosed in double quotation marks. The enclosed characters , plus a terminating \0 character automatically provided by the compiler, are stored in memory as a character string. The program uses several such character string constants, most often as arguments for the printf() and puts() functions. Note, too, that you can #define character string constants.

If you want to use a double quotation mark within a string, precede the quotation mark with a backslash, as follows :

 printf("\"Run, Spot, run!\" exclaimed Dick.\n"); 

This produces the following output:

 "Run, Spot, run!" exclaimed Dick. 

Character string constants are placed in the static storage class. Static storage means that if you use a string constant in a function, the string is stored just once and lasts for the duration of the program, even if the function is called several times. The entire quoted phrase acts as a pointer to where the string is stored. This action is analogous to the name of an array acting as a pointer to the array's location. If this is true, what kind of output should the program in Listing 11.2 produce?

Listing 11.2 The quotes.c program.
 /* quotes.c -- strings as pointers */ #include <stdio.h> int main(void) {     printf("%s, %p, %c\n", "We", "are", *"space farers");     return 0; } 

The %s format should print the string We . The %p format produces an address. So if the phrase "are" is an address, then %p should print the address of the first character in the string. (Pre-ANSI implementations might have to use %u or %lu instead of %p .) Finally, *"space farers" should produce the value of the address pointed to, which should be the first character of the string "space farers" . Does this really happen? Well, here is the output:

 We, 00410A40, s 
I l @ ve RuBoard


C++ Primer Plus
C Primer Plus (5th Edition)
ISBN: 0672326965
EAN: 2147483647
Year: 2000
Pages: 314
Authors: Stephen Prata

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net