gpt4 book ai didi

c++ - 为什么人们使用诸如 char*&buf 之类的东西?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:06:47 24 4
gpt4 key购买 nike

我正在阅读 Stack Overflow 上的一篇文章,我看到了这个函数:

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

char*& buf 在这里是什么意思,人们为什么要使用它?

最佳答案

这意味着 buf 是对指针的引用,因此它的值可以更改(以及它指向的区域的值)。

我在 C 中相当陈旧,但 AFAIK 在 C 中没有引用并且这段代码是 C++ (注意问题最初被标记为 )

例如:

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"
}

编辑:@brett 在评论中询问您是否可以将 NULL 分配给 buff,如果可以,使用引用的优势在哪里在一个指针上。我把答案放在这里是为了更好的可见性

You can assign NULL to buff. It isn't an error. What everyone is saying is that if you used char **pBuff then pBuff could be NULL (of type char**) or *pBuff could be NULL (of type char*). When using char*& rBuff then rBuff can still be NULL (of type char*), but there is no entity with type char** which can be NULL.

关于c++ - 为什么人们使用诸如 char*&buf 之类的东西?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3435976/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com