Not sure how to title this

Hi, I'm reading Charles Petzold's book on windows programming 5th edition. I'm reading chapter 2 about unicode and all that good stuff, I came across a little snippet of code I wanted to play with. The original snippet was just a declaration of an array like so:

 
static wchar_t a[] = L"Hello!";


I wanted to find out what it would look like in memory, so I started writing code like so:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>

using namespace std;

int main()
{
    static wchar_t * p;
    static wchar_t a[] = L"Hello!";
    cout << sizeof(a) << endl;
    p = &a[0];
    cout << *p << endl;
    cout << &a[0] << ", " << a[0] << endl;
    cout << &a[1] << ", " << a[1] << endl;
    cout << &a[2] << ", " << a[2] << endl;

    cout << *p+1 << ", " << &p+1 << ", " << p+1 << endl;
    cout << *p+2 << ", " << &p+2 << ", " << p+2 << endl;
}


and what I came out with was not what I expected. What I wanted the result to be was to print out the address of the element in the array, then print out the letter it corresponds to. However, what the result ended up being was the address of the element and a number next to each one 72, 101, and 108.

I'm just curious, what exactly is going on here because I am assuming 72 is the unicode for H and 101 is e, 108 is l but I'm not sure.

Can anyone please clarify what is going on for me? Thank you so much!
Last edited on
1
2
3
4
5
6
7
8
    static wchar_t * p;
    static wchar_t a[] = L"Hello!";
    cout << sizeof(a) << endl;
    p = &a[0];
    cout << *p << endl;
    wcout << &a[0] << ", " << a[0] << endl;
    wcout << &a[1] << ", " << a[1] << endl;
    wcout << &a[2] << ", " << a[2] << endl;


to print out wchar_t chars use wcout :D
if a is an array of wchar_t, then a[0] is a wchar_t, and &a[0] is it's address -- which is a wchar_t*, which ostream sees as the start of a null terminated string. => didn't register the Unicode/ansi confusion...

To see the actual address, cast it to an int. By convention memory addresses are given in hex, so it's

1
2
3
wcout << hex; // from <iomanip>, applies to all subsequent insertions
wcout << (int)&a[0] << L", " << a[0] << endl; // Unicode literals need an L
wcout << dec; // back to usual 


Last edited on
so just for my understanding, when I do:
 
cout << a[0] << endl;


and the result is 72, where is that result coming from ?
cout is printing a[0] (which is 'H') as an integer value. 72 is the ASCII code for 'H'
Ok thanks a lot guys, appreciate it so much!
Topic archived. No new replies allowed.