vrijdag 15 juni 2007

Pointers and Strings

The special relationship between arrays and pointers extends to C-style strings.
Consider the following code:

char flower[10] = "rose";
cout << flower << "s are red\n";

The name of an array is the address of the first element, so flower in the cout statement is the address of the char element containing the character r. The cout object asumes that the address of a char is the address of a string, so it prints the character at that address and then continues printing characters until it runs into the null character (\0). In short, if you give cout the address of a character, it prints everything from that character to the first null character that follows it.

The crucial element here is not that flower is an array name, but that flower acts as the address of a char. This implies that you can use a pointer-to-char variable as an argument to cout, also, because it, too, is the address of a char. Of course, that pointer should point to the beginning of a string.

But what about the final part of the preceding cout statement? If flower is actually the address of the first character in a string, what is the expression "s are red\n"? To be consistent with cout's handling of string output, this quoted string should also be an address. And it is!, for in C++ a quoted string, like an array name, serves as the address of its first element. The preceding code does not send the whole string to cout; it just sends the string address. This means strings in an array, quoted string constants, and strings described by pointers are all handled equivalently. Each is really passed along as an address. That's certainly less work then passing each and every character in a string.

REMEMBER
With cout and with most C++ expressions, the name of an array of char, a pointer-to-char, and a quoted string constant are all interpreted as the address of the first character of a string.

const char * bird = "wren"; // bird holds address of string

Means: bird is a pointer to const char, this means that you can modify the pointer address, but not the value where bird points to. Further more you see in this example that "wren" is treated as a address addressing the first element in the string. It is the compiler who prevents us from writing something to the character string constant!

CAUTION
When you read a string into a program, you should always use the address of previously allocated memory. This address can be in the form of an array name or of a pointer that has been initialized using new!

char animal[20] = "bear";
char * ps;

ps = animal; // sets ps to point to string
...
cout << animal << " at " << (int *) animal << endl;
cout << ps << " at " << (int *) ps << endl;

This produces the following output:

bear at 0x0065fd30
bear at 0x0065fd30

Normally, if you give cout a pointer, it prints an address. But if the pointer is type char *, cout displays the pointed-to string. If you want to see the address of the string, you have to type cast the pointer to another pointer type, such as int *, which this code does.
Note that assigning animal to ps does not copy the string! it copies the address.
This results in two pointers (animal and ps) to the same memory location and string.

To get a copy of a string, you need to do more. First you need to allocate memory to hold the string. You can do this by declaring a second array, or by using new. The second approach enables you to custom fit the storage to the string:

ps = new char[strlen(animal) + 1]; // get new storage

This code uses strlen() to find the length of the string; it adds one to get the length INCLUDING the null character. Then the program uses new to allocate just enough space to hold the string.

Next you need a way to copy a string from the animal array to the newly allocated space.

strcpy(ps, animal); // copy string to new storage

The strcpy() function takes two arguments. The first is the destination address, and the second is the address of the string to be copied. It's up to you to know for sure the destination address has enough space to copy the complete string to!
That's accomplished here by using the strlen() function to find the correct size and using new to get free memory.

Note that by using strcpy() and new, you get two separate copies of "bear":

bear at 0x0065fd30
bear at 0x004301c8

Also note that new located the new storage at a memory location quite distant from that of the array animal.

char food[20] = "carrots" // initialization
strcpy(food, "flan"); // otherwise

Note that something like this:

strcpy(food, "a picnic basket filled with many goodies");

can cause problems because the food array is smaller then the string!
In this case the function copies the rest of the characters into memory bytes immediately following the array, which can overwrite other memory the program is using! To avoid that problem you have to use strncpy() instead.
It takes a third argument: the maximum number of characters to be copied.
Be aware however, if this function runs out of space before it reaches the end of the string, it does NOT add the null character. Thus you should use the function like this:

strncpy(food, "a picnic basket filled with many goodies", 19);
food[19] = '\0';
This copies 19 characters into the array and then sets the last element to the null character. If the string is shorter than 19 characters, strncpy() adds a null character earlier to mark the true end of the string.

REMEMBER
Use strcpy() or strncpy(), not the assignment operator to assign a string to an array.

Geen opmerkingen: