I am reading a post on Stack Overflow and I saw this function:
advance_buf( const char*& buf, const char* removed_chars, int siz开发者_如何学Pythone );
What does char*& buf
mean here and why do people use it?
It means buf
is a reference to a pointer, so its value can be changed (as well as the value of the area it's pointing to).
I'm rather stale in C, but AFAIK there are no references in C and this code is C++ (note the question was originally tagged 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 can assign NULL
to buff
and if so where is the advantage of using a reference over a pointer. I'm putting the answer here for better visibility
You can assign
NULL
tobuff
. It isn't an error. What everyone is saying is that if you usedchar **pBuff
thenpBuff
could beNULL
(of typechar**
) or*pBuff
could beNULL
(of typechar*
). When usingchar*& rBuff
thenrBuff
can still beNULL
(of typechar*
), but there is no entity with typechar**
which can beNULL
.
buf
's a (C++) reference to a pointer. You could have a const char *foo
in the function calling advance_buf
and now advance_buf
can change the foo
pointer, changes which will also be seen in the calling function.
精彩评论