When I try to display the address of a char type variable, I don't get the normal hexidecimal address, but some strange symbols. I don't have the same problem with int or string, etc.. Example:

  char x='#';
  cout << &x;

The output of this is: #( (

What's the explanation?

Recommended Answers

All 12 Replies

I see nothing wrong with it spewing seemingly nonsense. Just like any number you have to convert it to a string somehow.

If I change char to int:

     int x=6;

cout << &x;

The output would be what's expect, an address: 0x28ff0c

You are leaning on your c++ compiler ability to convert a number to ascii. Think back to old C days. Now format it.

As this can be compiler dependent I would not lean on this too hard. Do it like we did in C.

Thanks for the link to the relevant thread. As for my Line 1, I don't think it's incorrect. I had x as a char type, not a pointer.

To go further we have to think and read more. To me you are setting the pointer's address to that single character so a pointer would be correct.

rprofitt, thanks for the replies, but please look at my original code again, I didn't have any pointer variable, just a char variable x, and then display its adress "&x". Isn't &var the address of any variable var, regardless its type? (or am I missing something?)

I looked but this is one of those common questions. Should I use a pointer to a single char? I'll write yes. It's not as if you initialized storage and then put the character into that memory location. You are saying "here's a character, now x points at that character." Hence you use the pointer to that string or char.

Isn't &var the address of any variable var, regardless its type? (or am I missing something?)

Yes, but you are missing something, namely that the cout << operator for a pointer to a char is overloaded so it works well for char arays (used to hold strings in C). It's a special case. It's defined to treat it as a pointer to a zero-delimited string. The nonsense you see is the ASCII interpretation of whatever bytes are at that address, up to the next zero.

I see, thanks James. So how to get the hexidecimal address of a char variable?

You can cast it so it's not a char pointer, eg cout << (void*) &x

Thank you!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.