Reputation: 986
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?
Upvotes: 1
Views: 65
Reputation: 726549
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.
Upvotes: 5