[英]Why do people use some thing like char*&buf?
I am reading a post on Stack Overflow and I saw this function: 我正在阅读有关Stack Overflow的帖子,我看到了这个功能:
advance_buf( const char*& buf, const char* removed_chars, int size );
What does char*& buf
mean here and why do people use it? char*& buf
在这里意味着什么?为什么人们会使用它?
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). 这意味着
buf
是对指针的引用,因此可以更改其值(以及它指向的区域的值)。
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 ) . 我在C中相当陈旧,但AFAIK在C中没有引用,这段代码是C ++ (注意问题最初标记为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. 编辑:在评论中@brett询问你是否可以为
buff
分配NULL
,如果是,那么在指针上使用引用的优势在哪里。 I'm putting the answer here for better visibility 我在这里提出答案以提高可见度
You can assign
NULL
tobuff
.您可以为
buff
分配NULL
。 It isn't an error.这不是错误。 What everyone is saying is that if you used
char **pBuff
thenpBuff
could beNULL
(of typechar**
) or*pBuff
could beNULL
(of typechar*
).大家都在说的是,如果你使用
char **pBuff
那么pBuff
可能是NULL
(char**
类型)或*pBuff
可能是NULL
(char*
类型)。 When usingchar*& rBuff
thenrBuff
can still beNULL
(of typechar*
), but there is no entity with typechar**
which can beNULL
.当使用
char*& rBuff
rBuff
仍然可以为NULL
(类型为char*
),但是没有类型为char**
实体可以为NULL
。
buf
'sa (C++) reference to a pointer. buf
(C ++)对指针的引用。 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. 您可以在调用
advance_buf
的函数中使用const char *foo
,现在advance_buf
可以更改foo
指针,这些更改也将在调用函数中看到。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.