Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Am I correctly understanding what all these pointers are pointing at?

Tags:

c++

I created a program that creates three c-strings, then an array of pointers the size of the amount of c-strings that I created (3), with each pointer in the array pointing at the first character of each of the three strings, and then finally a pointer to the array of pointers (which would be pointing at the first pointer in the array).

Here's the code:

    int main() {
    char arr1 [] = "hello";
    char arr2 [] = "dear";
    char arr3 [] = "world";

    char* p1[3];
    *p1 = arr1;
    *(p1+1) = arr2;
    *(p1+2) = arr3;
    char** ptr = p1;
}

However, when I do something like std::cout << *ptr << std::endl; I expect it to just output the ADDRESS of the first pointer in the array of pointers. However, it actually prints out the whole word "hello", which seems weird to me. I would expect an address, and if I outputted **ptr, I would expect for it to just print out the letter "h" (which it actually does)Am I not understanding something correctly? The same thing if I did std::cout << *(ptr+1)..I would expect the address of the second pointer in the array of pointers p1, but it actually prints out the whole word "dear." I'm so lost..I thought dereferencing ptr would give me the address to p1, which dereferencing it twice would give me the value inside of the address of p1.

like image 202
FrostyStraw Avatar asked Mar 23 '23 08:03

FrostyStraw


2 Answers

If you wanna print out the pointer, you should cast it to void pointer:

cout << (const void*) *ptr << endl;

because char * is actually old style C string, and there is an overloaded function:

std::ostream& operator << (std::ostream&, const char *);

that output the string instead of pointer address. For other pointers, it should just work fine.

like image 182
SwiftMango Avatar answered Apr 06 '23 08:04

SwiftMango


The "abnormalities" you see have nothing to do with pointers but with << operator.

std::cout << *ptr << std::endl;

is equivalent to

std::cout << arr1 << std::endl;

Thus overloaded << operator:

ostream& operator<< (ostream& os, const char* s);

is called. arr1 decays to const char* s. s is a treated as C string and printed until '\0'

like image 27
cpp Avatar answered Apr 06 '23 09:04

cpp