// returning a C-string as a pointer pointing to some dynamic memory #include #include using namespace std; char* subr(char[]); char* sub2(char[]); int main() { char name1[] = "George Washington"; char* p; char* q; int len; // This works because << is overloaded for char* cout << "The first president was " << name1 << " which has " << strlen(name1) << " bytes " << endl; // *name1 has type char, so this only prints one letter cout << "His name starts with " << *name1 << endl << endl; // Get some dynamic memory len = strlen("Abraham Lincoln"); cout << "Length is " << len << " bytes, so we need " << len + 1 << " bytes" << endl; p = new char[len+1]; // Load a value into it strcpy(p, "Abraham Lincoln"); // This works because << is overloaded for char* cout << "Another great president was " << p << " which has " << strlen(p) << " bytes" << endl; // *p has type char, so this only prints one letter cout << "His name starts with " << *p << endl << endl; // All of these are fine because the memory is pre-allocated q = subr(name1); cout << q << endl; cout << subr(name1) << endl; q = subr(p); cout << q << endl; cout << subr(p) << endl << endl; // And all of these are fine because the memory is dynamically // allocated in the function q = sub2(name1); cout << q << " has " << strlen(q) << " bytes" << endl; cout << sub2(name1) << " has " << strlen(sub2(name1)) << " bytes" << endl; q = sub2(p); cout << q << " has " << strlen(q) << " bytes" << endl; cout << sub2(p) << " has " << strlen(sub2(p)) << " bytes" << endl; // What you can't do is return a pointer to a local variable in the function // because that would be a dangling pointer (and the compiler will warn you) return 0; } // This function returns a pointer to pre-allocated memory char* subr(char* in_string) { return in_string; } // This function returns a pointer to some newly allocated dynamic memory char* sub2(char* in_string) { char* newp; newp = new char[strlen(in_string) + 1]; strcpy(newp, in_string); return newp; }