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;
3
  • 2
    Because defererencing a char* results in a plain char value. Commented Apr 3, 2014 at 7:19
  • 2
    An array is really just a pointer to the first element. Commented Apr 3, 2014 at 7:20
  • 1
    Array name is pointer to first element. Commented Apr 3, 2014 at 7:21

2 Answers 2

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

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

1 Comment

Thanks! Obviously the same with the outputstream printf in c
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

Comments

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.