1

I do not understand the following:

int main() {

    char ch[13] = "hello world";
    function(ch);

    return 0;
}

void function( char *ch) {

    cout << ch;

}

This outputs "hello world". But if I derefference the pointer ch the program outputs the first letter i.e. "h". I cannout figure out why.

cout << *ch;
songyuanyao
  • 169,198
  • 16
  • 310
  • 405
user2991252
  • 760
  • 2
  • 11
  • 28

2 Answers2

3

As someone stated in the comments section the result of derefferencing the pointer to an array is a plain char.

Let me explain why: Your ch pointer indicates the adress of the start of the char array, so when you call cout<<ch it will show on the screen all you have in the memory starting from the ch adress and goes secquentially till a first NULL value appears and stops. And when you call cout<<*ch it will take the value that you have stored on the start adress of the array which is h.

Derefferencing means that you take the value from a specific adress.

Hope it helped! :)

lrdTnc
  • 111
  • 2
1

When you pass an array into a function, either directly or with an explicit pointer to that array, it has decayed functionality, in that you lose the ability to call sizeof() on that item, because it essentially becomes a pointer.

So it's perfectly reasonable to dereference it and call the appropriate overload of the stream << operator.

More info: https://stackoverflow.com/a/1461449/1938163

Also take a look at the following example:

#include <iostream>
using namespace std;

int fun(char *arr) {
    return sizeof(arr);
}

int fun2(char arr[3]) {
    return sizeof(arr); // It's treating the array name as a pointer to the first element here too
}

int fun3(char (&arr)[6]) {
    return sizeof(arr);
}


int main() {

    char arr[] = {'a','b','c', 'd', 'e', 'f'};

    cout << fun(arr); // Returns 4, it's giving you the size of the pointer

    cout << endl << fun2(arr); // Returns 4, see comment

    cout << endl << fun3(arr); // Returns 6, that's right!

    return 0;
}

or try it out live: http://ideone.com/U3qRTo

Community
  • 1
  • 1
Marco A.
  • 43,032
  • 26
  • 132
  • 246