0

In many examples I see, if int x = 0; int *ptr; ptr = &x then ptr is saving x's address info. I'm kinda confused why if the following code does perform the same. When I print the ptr, it shows:

app

rather than the address of the p[0].

#include <iostream>
#define show(a)     std::cout<<a<<std::endl;
#define Syswait     std::system("pause");

int main() {


char p[] = "app";
char *ptr;
ptr = &p[0];
show(ptr);

Syswait;
}

Can anyone explain? Thanks.

User800222
  • 351
  • 4
  • 16

2 Answers2

2

Because that is what the function is declared to do. ptr is a char* (char pointer) and there is an overload specifically defined to accept it.

std::cout<<a

actually calls the function declared as:

template< class Traits >
basic_ostream<char,Traits>& operator<<( basic_ostream<char,Traits>& os,  
                                        const char* s );

From the link we learn what the function will do:

After constructing and checking the sentry object, inserts successive characters from the character array whose first element is pointed to by s.

To avoid this, cast to void *:

std::cout << (void *)a;
o11c
  • 15,265
  • 4
  • 50
  • 75
wally
  • 10,717
  • 5
  • 39
  • 72
2

The pointer actually doing its job. It's not the pointer actually but it's the cout that you have to observe.

Consider the following code

#include<iostream>
using namespace std;
int main(){
Char p[ ] = "app";
Cout<<p<<endl;
Return 0;
}

In the above code cout<<p<<endl; p will output the address of 0th index of p. If you use pointer to store the 0th index it is the same.

Cout will consider pointer of char variable as cstring and hence prints all the characters of the array.

You are doing the same using pointer.