简体   繁体   English

为什么人们会使用像char *和buf这样的东西?

[英]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中相当陈旧,但AFAIK在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 to buff . 您可以为buff分配NULL 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* ). 大家都在说的是,如果你使用char **pBuff那么pBuff可能是NULLchar**类型)或*pBuff可能是NULLchar*类型)。 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 . 当使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM