pass char** which is a pointer to a pointer, like this

void foo( char ** ptr)
{
   *ptr = new char[255];
}

int mian()
{
   char *ptr = 0;
   foo( &ptr );

   <snip>
   return 0;
}

Or of course you can pass it by C++ reference like:

void foo( char *& ptr)
{
   ptr = new char[255];
}

int mian()
{
   char *ptr = 0;
   foo( ptr );

   <snip>
   return 0;
}

Edited 3 Years Ago by Dani: Formatting fixed

The method I posted is from C language, while thekashap's method is c++. One is not safer than the other. Which method you choose would be a personal preference but in a c++ program you should probably use the c++ method for consistancy.

Just one addition, in case of passing by pointer you would be dereferencing the pointer to pointer everytime you use it. Although compilers may optimize it. A reference works as an alias.

How to pass char* as refrence in a funstion?

based on these two methods is there any gain over one, is one safer than another?

thanks

Seems like someone asked the question, some else read read the answers and followed up with more question and finally someone understood all and thanked. :)
If solved mark the thread as solved..

Seems like someone asked the question, some else read read the answers and followed up with more question and finally someone understood all and thanked. :)
If solved mark the thread as solved..

the information provided in this thread has been an awesome resource.

at first i was going huh? ** or *& but now it makes sense to me :-D


http://www.cplusplus.com/doc/tutorial/pointers.html

is a recomended read for anyone confused about pointers.

i read this site one nite and had somewhat of an epiphany lol

the site helped me to understand pointers and their usefullness.

As a rule of thumb, if you need to modify a variable in another function, you need to pass an address of it to the called function.

In this case you wanted to modify the char pointer and hence need to pass the pointer to the char pointer i.e. the address of the char pointer. References in C++ are just glorified pointers which act as the syntactic sugar.

This question has already been answered. Start a new discussion instead.