... dangerous
23 // assignment. If string1 is modified, pointer ptr1 can
24 // become invalid.
25 ptr1 = string1.data(); // non-null terminated char array
26
27 // output each character using pointer
28 for (size_t i{0}; i < length; ++i) {
29 cout << *(ptr1 + i); // use pointer arithmetic
30 }
31
32 cout << "\nptr2 is " << ptr2 << endl;
33 delete [] ptr2; // reclaim dynamically allocated memory
34 }
string string1 is STRINGS string1 converted to a pointer-based string is STRINGS ptr1 is STRINGS ptr2 is 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 ...
Get C++ How to Program, 10/e now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.