|
-
February 2nd, 2005, 11:14 PM
#1
Passing address of a char* and then initializing and setting it
Say we have a function that calls Func2:
void Func1()
{
char* str1;
Func2(&str1);
std::cout<<str1;
}
Func2 does the following:
void Func2(char** str2)
{
*str2=new char[10];
strcpy(*str2,"Hello")
}
When execution goes into Func1, following things happen:
1. It is seen that the address of str1 is taken. So, str1 is allocated on the stack. The address of str1 is given to Func2.
2. Func2 is called and address of str1 is given to str2. str1 is given a valid address(by saying *str2=new char[10])
3. str1 is given the string "Hello" - by saying strcpy(*str2,"Hello")
4. When Func2 ends, execution goes back to Func1. The line std::cout<<str1 prints "Hello"
I believe I am correct?
Thanks
Vikram
-
February 2nd, 2005, 11:41 PM
#2
Re: Passing address of a char* and then initializing and setting it
Yes, that's right.
Just a reminder, don't forget to delete[] str1 when it is not needed.
-
February 3rd, 2005, 07:26 AM
#3
Re: Passing address of a char* and then initializing and setting it
 Originally Posted by vikrampschauhan
When execution goes into Func1, following things happen:
1. It is seen that the address of str1 is taken. So, str1 is allocated on the stack. The address of str1 is given to Func2.
2. Func2 is called and address of str1 is given to str2. str1 is given a valid address(by saying *str2=new char[10])
3. str1 is given the string "Hello" - by saying strcpy(*str2,"Hello")
4. When Func2 ends, execution goes back to Func1. The line std::cout<<str1 prints "Hello"
I believe I am correct?
Except for the "str1 is allocated on the stack" (where it resides is compiler dependent), yes, you are correct.
Hopefully you don't write real C++ code this way for dealing with string data.
Regards,
Paul McKenzie
-
February 3rd, 2005, 02:22 PM
#4
Re: Passing address of a char* and then initializing and setting it
Just a note, if you do find it absolutely necessary to write code like this, you may consider your function taking a reference-to-pointer-to-char as opposed to pointer-to-pointer-to-char. This way, when you call the function, you don't have to explicitly take the address of the pointer. Also, in the function itself, you don't have to keep derefernecing the variable:
void Func1()
{
char* str1;
Func2(str1); // no &
std::cout<<str1;
}
Func2 does the following:
void Func2(char*& str2)
{
str2=new char[10]; // no *
strcpy(str2,"Hello") // no *
}
Old Unix programmers never die, they just mv to /dev/null
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|