I run the follow code:

    #include <iostream>

    using namespace std;

    typedef struct Test
    {
        char   a;
        char   b;
        int    i;
        double d;
    }Test;

    int main()
    {
        Test test;
        test.a = 'a';
        test.b = 'b';
        test.i = 478;
        test.d = 4.7;

        cout << &test.a << '\n'
             << &test.b << '\n'
             << &test.i << '\n'
             << &test.d << '\n';

        return 0;
    }

The output is:

    ab@
    b@
    0x28fe94
    0x28fe98

At first, i thought it is a result of the precedence between & and ..
But the 0x28fe94 and 0x28fe94 indicate it's not the problem of precedence.
I can figure out what does the ab@ and b@ mean?

有帮助吗?

解决方案

When you write

 cout << &test.a

because test.a is a char, this will invoke the operator<< (ostream&, const char*) overload, thinking that your char* is a pointer to a C-style string rather than a pointer to just one character. Consequently, the operation will start reading bytes starting at the memory address of &test.a until it finds a null terminator (a zero byte). This happens to print out ab@, since a has value 'a', b has value 'b', and the number 478, on your system, happens to correspond to an @ character followed eventually by a null byte.

If you want to see the numeric addresses of test.a and test.b, cast the pointers to void*s, which will select the operator<< (ostream&, const void*) overload. For example:

cout << static_cast<void*>(&test.a)

Hope this helps!

其他提示

It means undefined behaviour. There's a special overload for const char * that prints it as a null-terminated string. Yours has no terminator, so it goes beyond and triggers the aforementioned UB. Fix it with a cast:

std::cout << static_cast<void *>(&test.a) << '\n'
          << static_cast<void *>(&test.b) << '\n'
          << &test.i << '\n'
          << &test.d << '\n';

Because you are passing the address of a character when you use &test.a and &test.b, the cout operator is treating the addresses as the start of a string. That's why you get first ab@ and then b@. The @ is less obvious; it falls in the padding after the two char values and before the int value in the structure, and is quasi random junk. You're actually invoking undefined behaviour because you're asking the output code to access the padding. If you want to print addresses, cast to void *. If you want to print characters, don't supply the address.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top