user3885616
user3885616

Reputation:

Basic pointer issue

I've posted a few pointer-related questions recently. I've tried to unite the confusion I'm suffering in this one post, so apologies if it looks familiar. The question is - why does funky() output the string whereas funkier() outputs the address? My logic tells me that the latter is what I would expect. Or is this just the way std::cout deals with things?

I notice that printf behaves the same way.

#include <iostream>
using namespace std;

void funky(const char* a);
void funkier(char* a[]);

int main() {
    const char* y = "message";
    funky(y);

    char* z[3];
    z[0] = "one";
    z[1] = "two";
    z[2] = "three";
    funkier(z);

    cin.get();
    return 0;
}

void funky(const char* a) {
    cout << a << endl; // prints the string.
}

void funkier(char* a[]) {
    cout << a << endl; // prints the address.
}

Upvotes: 0

Views: 107

Answers (1)

rodrigo
rodrigo

Reputation: 98338

The operator<< for std::ostream is overloaded for many different types of the right operand.

If the second operand is a const char* it is interpreted as a NUL-terminated string and printed.

If the second operand is a const void* it is printed as an address.

There are many other overloads, but these are not relevant here.

The funky() call uses the first overload.

But the funkier argument is actually a char**, which is neither of the above. But it is convertible to const void*, not to const char*, so the second overload is used.

Beware of printf()! That is a C function and it does not detect the type of the arguments. It expects you to pass the right %s or %p or whatever for each of the arguments. If you use the wrong letter, or pass the wrong argument type, you will probably get Undefined Behaviour.

char *x = "a";
printf("%s", x); //prints x as string
printf("%p", x); //prints x as pointer
printf("%d", x); //Undefined Behaviour!!!
printf("%d", (int)x); //prints the pointer value as an integer, if it fits

Upvotes: 5

Related Questions