简体   繁体   中英

Why am I unable to obtain memory address of char or uint8_t variables in MSVS2019 / C++?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM