简体   繁体   中英

Pointers and Arrays [ pointers to int vs pointers to char]

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM