-2

I'm working on learning pointers in C++, and was doing fine with int*, double*, etc. but then I tried something that I can't understand. I've attached my code segment, and the comments are the terminal output.

char word[] = "Hello there";
    cout << word << endl; //Hello there
    cout << *word << endl; //H
    cout << &word << endl; //Address

    char *wordpt = word;
    cout << wordpt << endl; //Hello there
    cout << *wordpt << endl; //H
    cout << &wordpt << endl; //Address

    wordpt = &word[0];
    cout << wordpt << endl; //Hello there
    cout << *wordpt << endl; //H
    cout << &wordpt << endl; //Address

What's going on in these? I don't even understand how the contents of word (*word) can be a single index. How is word stored in memory? And why would wordpt allow me to give it a value of word, which isn't an address?

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
Alex G
  • 747
  • 4
  • 15
  • 27
  • Didn't know about array decaying. Sorry everyone. Marking as solved when the timer finishes counting to 5 mins. – Alex G Mar 05 '15 at 00:54

1 Answers1

1

The pointer wordpt in the first case points to the first element of the array word, the second assignment is exactly the same thing but explicitly.

Arrays are automatically converted to pointers to their first elements as is specified by the c standard which also applies to c++.

What is confusing you is the fact that cout automatically prints the contents of a char * pointer instead of the address the pointer points to, to do it there is a requirement, the pointed to data must be a c string, i.e. a sequence of non-nul bytes followed by a nul byte, which is what is stored in word.

So cout is accessing the data pointed to by the wordpt pointer.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97