1

Why do pointers behave differently when they are pointing to an integer array and a character array?

For example

int num[] = {1,2,3};
cout << num ;

This prints out the ADDRESS of the first element

char list[] = { '1', '2', '3'};
cout << list ;

This prints out the VALUE of entire elements of array!

Likewise

cout << (num+1) ;

prints out the ADDRESS of the second element. While

cout << (list+1);

prints out the VALUE of entire array beginning from the second element

From my understanding, array name is a pointer to the first element of the array. Without the dereference operator(*), the pointer should return the address of the element. But why is the char pointer returning the value?

3
  • The different is that operator<< is an overloaded function, and there is a different overload for char * than for other pointer types Commented Apr 8, 2017 at 3:21
  • C is not C++ is not C. Don't spam tags! Commented Apr 8, 2017 at 4:05
  • I didn't realize this problem was specifically for C++. I thought this was related to the Pointers & array concept as a whole. Sorry Commented Apr 8, 2017 at 4:45

1 Answer 1

5

It is not pointers behaving differently: the behavior is how C++ standard library handles pointer output.

Specifically, operator << has a non-member overload for const char *, which handles null-terminated C strings. This is the overload applied to printing char array. Note that your character array is not null-terminated, so printing it produces undefined behavior. You can fix this by adding zero to the array of characters:

char list[] = { '1', '2', '3', '\0'};

There is also an overload that takes void *, which applies to printing an int pointer.

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

1 Comment

You can just use 0 instead of'\0.

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.