Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do people use some thing like char*&buf?

Tags:

c++

I am reading a post on Stack Overflow and I saw this function:

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

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

like image 961
brett Avatar asked Aug 08 '10 20:08

brett


People also ask

Why do we use char * in C++?

But as humans, we like to read and write using the characters of our respective languages. That's why a character type is integrated into programming languages like C++. char allows you to store individual characters or arrays of characters and manipulate them.

Why do we use char?

The char type is used to store single characters (letters, digits, symbols, etc...).

What does char * a means?

char a[] means character array ie each index has a value. For example char a[2]={'r','g'}; Here a[0]='r' and a[1]='g'. This values are stored in stack or data section depending on the storage class. char *a[2] means array of character pointers ie each index stores address of strings.

Why is a char * a string?

char *A is a character pointer. it's another way of initializing an array of characters, which is what a string is. char A, on the other hand, is a single char. it can't be more than one char.


1 Answers

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 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.

like image 57
Motti Avatar answered Oct 05 '22 01:10

Motti