I am learning c++. I am learning about pointers, the free store and how to use it. At the end of this code i am trying to release memory used by the pointer pname. what am I doing wrong?
Please use the code format tag to format the code you post. You can edit the post rather than posting again. char* pname; // This declares your pointer -- good
pname = newchar; // This allocates 1 byte of the heap and pnane points to it
cout << "Please input your name: "<<endl;cin.get(pname,15,'\n'); // This reads upto 15 bytes into the allocated block, but you only allocated 1 byte, not 15
A dynamically allocated region of memory must be re-allocated in order for its size to change. The standard vector[1] is an array which can grow and shrink to your specifications.
Ok now Im confused, Im trying to create a dynamic pointer and using cin.get() mainly to allow flexibility and end the string at the '\n' character. I am a beginner so throwing in the vector terminology is un-needed its only confused. is there a better way?
The only way I can think of is a linked-list. If you don't already know, a linked-list is a chain of pointers. More specifically, this:
1 2 3 4 5 6 7 8 9
struct SOListNode
{
SOListNode *pNextNode;
};
SOListNode *pSIRootNode = new SOListNode;
pSIRootNode->pNextNode = new SOListNode;
pSIRootNode->pNextNode->pNextNode = new SOListNode;
// ...and so on.
In you case, your structure would appear like this: