string test(char *ptr);
int main ()
{
string message = "test";
char *ptr = newchar [message.length()+1];//pointer allocates the memory for message including a null character
strcpy(ptr, message.c_str()); //assuming it copies the entire string in to the pointer.
string store = test(ptr);
//cout << ptr << endl; prints the entire string
//cout << *(ptr) << endl; prints the character the pointer is pointing to in this case the first character
delete []ptr;
Pointers is what I hate. I don't understand what is going on.
I have created a pointer and allocated memory for the string.
Since ptr is pointing to the memory allocated of 'message'. I should be able to initialize a pointer as an argument of the function.
What does this pointer point to?
The entire memory block of 'message' or the first letter.
Strings are arrays of characters. So I know that if I pass the address of the first cell (which is pass by reference) of the string, everything is followed over.
ptr refers to the complete array, *ptr to the first char,
Why do you use pointers if you hate them ?
In C++ there is rarely a need for them, unless you write a STL like container like vector, list.