Click to See Complete Forum and Search --> : Passing address of a char* and then initializing and setting it


vikrampschauhan
February 2nd, 2005, 10:14 PM
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

Kheun
February 2nd, 2005, 10:41 PM
Yes, that's right.

Just a reminder, don't forget to delete[] str1 when it is not needed.

Paul McKenzie
February 3rd, 2005, 06:26 AM
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

HighCommander4
February 3rd, 2005, 01:22 PM
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 *
}