开发者

Printing the address of a struct object

开发者 https://www.devze.com 2023-01-03 04:01 出处:网络
I have a struct like this typedef struct _somestruct { int a; int b; }SOMESTRUCT,*LPSOMESTRUCT; I am creating an object for the struct and trying to print it\'s address like this

I have a struct like this

typedef struct _somestruct {
    int a;
    int b;
}SOMESTRUCT,*LPSOMESTRUCT;

I am creating an object for the struct and trying to print it's address like this

int main()
{
    LPSOMESTRUCT val = (LPSOMESTRUCT)malloc(sizeof(SOMESTRUCT));

    printf("0%x\n", val);

    return 0;
}

..and I get this warning

warning C4313: 'printf' : '%x' in format string conflicts with argument 1 of type 'LPSOMESTRUCT'

So, I tried to cast the address to int like this

printf("0%x\n", static_cast<int>(开发者_运维百科val));

But I get this error:

error C2440: 'static_cast' : cannot convert from 'LPSOMESTRUCT' to 'int'

What am I missing here? How to avoid this warning?

Thanks.


%x expects an unsigned. What you're printing is a pointer. To do that correctly, you normally want to use %p. To be pedantically correct, that expects a pointer to void, so you'll need to cast it:

printf("%p\n", (void *)val);

In reality, most current implementations use the same format for all pointers, in which case the cast will be vacuous. Of course, given the C++ tag, most of the code you've included becomes questionable at best (other than the parts like LPSOMESTRUCT, which are questionable regardless). In C++, you normally want something more like:

struct somestruct { 
   int a;
   int b;
};

somestruct *val = new somestruct; // even this is questionable.

std::cout << val;


Use the %p format specifier to print a pointer.

printf("%p\n", val);


If you want to cast then using reinterpret_cast instead of static_cast might do the trick here.

With printf try using the %zu instead of %x for printing out a pointer because the pointer is of unsigned integer type (ie %zu).

printf("%zu \n", val);

Just one other thing, being a c++ program is there a reason why you are using malloc instead of new?


As this is tagged C++, can I just point out that you do not need typedefs when creating structs in that language:

typedef struct _somestruct {
    int a;
    int b;
}SOMESTRUCT,*LPSOMESTRUCT;

should be:

struct SOMESTRUCT {
    int a;
    int b;
};

Also, it is considered by many to be bad practice to create typedefs like LPSOMESTRUCT which hide the fact that a type is a pointer.

0

精彩评论

暂无评论...
验证码 换一张
取 消