char
* StringsYou can convert string
class objects to pointer-based strings. As mentioned earlier, unlike pointer-based strings, string
s are not necessarily null terminated. These conversion functions are useful when a given function takes a pointer-based string as an argument. Figure 21.9 demonstrates conversion of string
s to pointer-based strings.
The program declares a string
, a size_t
and two char
pointers (lines 8–11). The string string1
is initialized to "STRINGS"
, ptr1
is initialized to nullptr
and length
is initialized to the length of string1
. Memory of sufficient size to hold a pointer-based string equivalent of string string1
is allocated dynamically and attached to char
pointer ptr2
.
Line 14 uses string
member function copy
to copy object string1
into the char
array pointed to by ptr2
. Line 15 places a terminating null character in the array pointed to by ptr2
.
Line 19 uses function c_str
to obtain a const char
* that points to a null terminated pointer-based string with the same content as string1
. The pointer is passed to the stream insertion operator for output.
Line 25 assigns the const char
* ptr1
a pointer returned by class string
member function data
. This member function returns a non-null-terminated built-in character array. We do not modify string string1
in this example. If string1
were to be modified (e.g., the string
’s dynamic memory changes its address due to a member function call such as string1.insert(0, "abcd"
);
), ptr1
could become invalid—which could lead to unpredictable results.
Lines 28–30 use pointer arithmetic to output the character array pointed to by ptr1
. In lines 32–33, the pointer-based string ptr2
is output and the memory allocated for ptr2
is delete
d to avoid a memory leak.
Not terminating the character array returned by data
with a null character can lead to execution-time errors.