Why do people use something like char * & buf?

I am reading a stack overflow message and I saw this function:

advance_buf( const char*& buf, const char* removed_chars, int size ); 

What does char*& buf mean and why do people use it?

+6
c ++
source share
2 answers

This means that buf is a pointer to a pointer, so its value can be changed (as well as the value of the area it points to).

I'm pretty obsolete in C, but AFAIK there are no references in C, and this code is C ++ (note that the question was originally tagged with c ).

For example:

 void advance(char*& p, int i) { p += i; // change p *p = toupper(*p); // change *p } int main() { char arr[] = "hello world"; char* p = arr; // p -> "hello world"; advance(p, 6); // p is now "World" } 

Edit: In the comments, @brett asked if you could assign NULL to buff , and if so, where is the advantage of using a link over a pointer. I put the answer here for better visibility.

You can assign a NULL buff . It's not a mistake. Everyone says that if you used char **pBuff , then pBuff can be NULL (like char** ) or *pBuff can be NULL (like char* ). When using char*& rBuff then rBuff can be NULL (of type char* ), but there is no object of type char** , which can be NULL .

+13
source share

buf a (C ++) reference to a pointer. You can have const char *foo in the function calling advance_buf , and now advance_buf can change the pointer foo , changes that will also be visible in the calling function.

+4
source share

All Articles