0

I need to obtain the memory address for some of the variables in my program. I have no issues getting addresses of 2 or 4 byte variables of type short, int, uint32_t, etc. However when I try to get address of 1 byte variable, I get a garbled text on the console, instead of numerical address.

Here is the code that I'm working with:

#include <iostream>

int main()
{
    char test2[16] = { 'a','b','c','d','e','f' };
    std::cout << "test2 memory address: " << &test2 << std::endl;

    int a = 69;
    uint8_t b = 69;
    //int x = (int)&b;
    char z = 0x33;
    short z1 = 0x1551;

    std::cout << "memory address: int a " << &a << std::endl;
    std::cout << "memory address: uint8_t b " << &b << std::endl;
    std::cout << "memory address: char z " << &z << std::endl;
    std::cout << "memory address: short z1 " << &z1 << std::endl;

return 0;
}

Console output:

test2 memory address: 0075FE28
memory address: int a 0075FE04
memory address: uint8_t b E╠╠╠╠╠╠╠╠E
memory address: char z 3╠╠╠╠╠╠╠╠√²u
memory address: short z1 0075FDD4

Using built in "memory view" in debugging mode, I can see the 1 byte variables and they should have the following addresses: b: 0075fdfb z: 0075fde3

Can someone pinpoint what am I doing wrong?

parameter2
  • 13
  • 2
  • streams will treat `char*` as a null-terminated string. You might have to just reinterpret_cast them all to a size_t to make it print properly, or use printf with %d – parktomatomi Dec 09 '19 at 01:34
  • `(void*)&b` and `(void*)&z`. (or see paxdiablo answer for using `static_cast`) – David C. Rankin Dec 09 '19 at 01:36
  • Does this answer your question? [Why is address of char data not displayed?](https://stackoverflow.com/questions/4860788/why-is-address-of-char-data-not-displayed) – phuclv Dec 09 '19 at 01:48
  • there are a lot of duplicates: [Why C++ would not print the memory address of a char but will print int or bool? (duplicate)](https://stackoverflow.com/q/13535254/995714), [“cout” and “char address” (duplicate)](https://stackoverflow.com/q/29188668/995714), [cout not printing unsigned char](https://stackoverflow.com/q/15585267/995714), [Why does streaming a char pointer to cout not print an address?](https://stackoverflow.com/q/10869459/995714)... – phuclv Dec 09 '19 at 01:49

1 Answers1

3

Stream output will treat certain types as legacy C strings (such as char * for example) and therefore assume you want to print the string behind the pointer.

To fix this, just turn it into a type that the stream won't treat as a legacy C string, something like:

#include <iostream>
char xyzzy[] = {'h', 'e', 'l', 'l', 'o', '\0'};
int main() {
    std::cout << xyzzy << '\n';
    std::cout << reinterpret_cast<void*>(xyzzy) << '\n';
}

You'll see the first one prints out the entire string while the latter treats it as a pointer.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953