I'm teaching myself C++ and I'm a bit confused about pointers (specifically in the following source code). But first, I proceed with showing you what I know (and then contrasting the code against this because I feel as if there are some contradictions going on).
What I know:
int Age = 30;
int* pointer = &Age;
cout << "The location of variable Age is: " << pointer << endl;
cout << "The value stored in this location is: " << *pointer << endl;
Pointers hold memory addresses. Using the indirection (dereference) operator (the *), you can access what is stored in memory location of the pointer. Onto the code in this book I'm having trouble understanding...
cout << "Enter your name: ";
string name;
getline(cin, name); //gets full line up to NULL terminating character
int CharsToAllocate = name.length() + 1; //calculates length of string input
//adds one onto it to adjust for NULL character
char* CopyOfName = new char[CharsToAllocate];
// pointer to char's called CopyOfName, is given the memory address of the
//beginning of a block
//of memory enough to fit CharsToAllocate. Why we added 1? Because char's need a
//NULL terminating character (\0)
strcpy(CopyOfName, name.c_str()); //copies the string name, into a pointer?
cout << "Dynamically allocated buffer contains: " << CopyOfName << endl;
delete[] CopyOfName; //always delete a pointer assigned by new to prevent memory leaks
Output:
Enter your name: Adam
Dynamically allocated buffer contains: Adam
The comments in the above code are my comments. My problem begins with strcpy
. Why is name.c_str()
copied into a pointer CopyOfName
? Does this mean that all strings are essential pointers? So like
string testing = "Hello world";
Is actually a pointer pointing to the memory location where "H" is stored?
Next, why is it in the print out statement using CopyOfName
and not *CopyOfName
? Pointers hold memory addresses? Using *CopyOfName
would print out the contents of the memory location. I tried this in Code::Blocks and if the input text was "Hello World." Using *CopyOfName
in the print out statement would just give an "H". This makes sense since when I declared that I needed a memory block with the 'new' thing, this actually returns a pointer to the first part of the dynamically allocated memory block.
The only way I can reconcile this is if a string is actually a pointer.
string testing = "Confused";
cout << testing << endl;
would print out the word "Confused"
However, if I try to compile
string testing = "Confused";
cout << *testing;
I get an error message.
Basically, to summarize my question, I'm trying to understand the code with strcpy
and the cout
statement.