Function receiving a pointer to a string.

Write your question here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
string test(char *ptr);


int main ()
{
	string message = "test";
	
	char *ptr = new char [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.
Last edited on
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.
It's part of my project.
How do I pass a pointer to the function?
Last edited on
You do already pass pointers to functions in:
1
2
strcpy( ptr, message.c_str() );
string store = test( ptr );
I mean into an actual function not it's class member functions.

line 2 doesn't work for me
Both 'strcpy' and 'test' are standalone functions. Besides, a function is a function; they all take parameters -- either by value or by reference.

Yes, the string::c_str() is a member, but you don't pass any pointer to it.
The message.c_str() is a pointer that you pass to function 'strcpy'.

doesn't work

Doesn't exist. You either have an exact error (that you show to us) or you don't have a problem.


EDIT: I see that you have created a new thread on same topic: http://www.cplusplus.com/forum/beginner/246915/
That is double-posting. Double-posting is wasting everybody's time.
Last edited on
Topic archived. No new replies allowed.