3

I'm trying to understand pointers and and arrays in C++. I've noticed that in the following code outputting a correctly gives the address of the first element in array, however outputting c gives pk rather than an address.

int array[3]={4,7,2};
int * a;

a= array;

char Carray[3]={'p','k','\0'};
char * c;

c= Carray;

cout << a << "\n";
cout << c << "\n";

Is this the incorrect way to find the address of the first element in Carray? Or is this some quirk of how cout interprets pointers for integer and character arrays.

Output:

Ox23fe30
pk
3
  • Please show us the output that you get from those statements. Commented Jul 16, 2014 at 16:26
  • C-style strings are char arrays ending in a null char \0, and cout is assuming you are passing it a C-style string. So your method of getting the address of first element is correct, but cout's interpretation of that address is different for int and char. Commented Jul 16, 2014 at 16:28
  • Unless you are specifically asking for comparisons with C or something like that, don't tag your C++ questions with C - the languages and their idiomatic answers can be very different. Commented Jul 16, 2014 at 16:29

5 Answers 5

7

It's a quirk of how cout interprets pointers for character arrays.

When given a pointer, cout will print the address, unless it is a char*, in which case it interprets the pointer as a c-style-string (pointer to an array of chars ending will a null byte).

To print the address of a char array, cast it to void* first: cout << reinterpret_cast<void*>(c) << "\n";

Sign up to request clarification or add additional context in comments.

Comments

5

With c, you're calling operator<<(std::istream&, char*). That just prints the characters until it hits '\0', like a regular old C-style string.

With a, operator<<(std::istream&, int*) prints the address.

1 Comment

Technically I think the overload is operator<<(std::istream&, void*)
1

It is a "quirk" from C. In C, a string of characters is a null-terminated char[]. cout allows for using C-style strings, so it outputs the character pointer as if it is a string.

Comments

0

cout interprets char pointers in different way than say int pointers, so your way of getting the address of the first array element is ok.

Comments

0

A pointer to char is generally treated as a NULL-terminated string in C and C++. For an STL stream such as cout, a char pointer is definitely treated as a NULL-terminated string.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.