0

I have been analyzing code and I came across this:

...
vector <char> buffer (size + 1);
vsnprintf (& buffer [0], buffer.size (), format, args);
printf (& buffer [0]);
...

So I was wondering why it prints all the characters and in the vnsprinft function, the reference to the first element of the vector is passed

surreal Ceres
  • 35
  • 1
  • 5

1 Answers1

0

So, as others have mentioned, this is due to the fact that you are not actually passing by reference, you're actually passing the address. This is because the & has different meanings in different contexts.

In a function declaration context, it means passing by reference:

void myFunc(int& i) { // << pass by reference
    std::cout << i;
}

When you call such a function, you don't need the &:

int main () {
    int i = 3;

    myFunc(i); // << still passing by reference even though you aren't using the & here


    return 0;
}

On the other hand, using an & when you call a function means taking an address of that variable. It's just like doing this:

int main () {
    int i = 3;
    int * ptr = &i; // gets the address of i


    return 0;
}

Here, we're getting a pointer to i, not getting a reference to it.

It's the same for functions. Here is a function example:

void myFunc(int* i) { // << passing the address of a variable
    if(i != nullptr) {
        std::cout << *i;
    }
}
int main () {
    int i = 3;

    myFunc(&i); // << Now we're passing the address of i


    return 0;
}

So that's the first part of what's going on.


So, why does this result in printing all the characters? Well, you're basically running into this problem, just with a few layers between you and the character pointer. As mentioned in one of the answers, char *s are an old way of representing strings. Thus, a lot of functions treat char* as a string, not a single character.

So, how are you getting a char * from an std::vector? Well, suffice it to say you're doing it accidentally by using the &. Since std::vectors have continuous memory, you basically end up with a valid char *.