user2991252
user2991252

Reputation: 788

Pointer to character array in C++

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;

Upvotes: 1

Views: 118

Answers (2)

lrdTnc
lrdTnc

Reputation: 111

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! :)

Upvotes: 3

Marco A.
Marco A.

Reputation: 43662

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

Upvotes: 1

Related Questions