简体   繁体   English

打印结构对象的地址

[英]Printing the address of a struct object

I have a struct like this 我有这样的struct

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 我正在为struct创建一个对象,并试图像这样打印它的地址

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' 警告C4313:'printf':格式字符串中的'%x'与'LPSOMESTRUCT'类型的参数1冲突

So, I tried to cast the address to int like this 所以,我试着像这样把地址转换为int

printf("0%x\n", static_cast<int>(val));

But I get this error: 但我得到这个错误:

error C2440: 'static_cast' : cannot convert from 'LPSOMESTRUCT' to 'int' 错误C2440:'static_cast':无法从'LPSOMESTRUCT'转换为'int'

What am I missing here? 我在这里错过了什么? How to avoid this warning? 如何避免这种警告?

Thanks. 谢谢。

%x expects an unsigned. %x期望无符号。 What you're printing is a pointer. 你打印的是一个指针。 To do that correctly, you normally want to use %p . 要正确执行此操作,通常需要使用%p To be pedantically correct, that expects a pointer to void, so you'll need to cast it: 为了迂腐正确,这需要一个指向void的指针,所以你需要将它转换为:

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). 当然,考虑到C ++标签,你所包含的大多数代码都充其量是有问题的(除了像LPSOMESTRUCT之类的部分,无论如何都是有问题的)。 In C++, you normally want something more like: 在C ++中,您通常需要更多类似的东西:

struct somestruct { 
   int a;
   int b;
};

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

std::cout << val;

使用%p格式说明符打印指针。

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

If you want to cast then using reinterpret_cast instead of static_cast might do the trick here. 如果你想使用reinterpret_cast而不是static_cast进行强制转换,可以在这里诀窍。

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而不是%x来打印指针,因为指针是无符号整数类型(即%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? 另外一件事,作为一个c ++程序,你有没有理由使用malloc而不是new?

As this is tagged C++, can I just point out that you do not need typedefs when creating structs in that language: 由于这是标记的C ++,我可以指出在使用该语言创建结构时不需要typedef:

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. 此外,许多人认为创建像LPSOMESTRUCT这样的typedef是一种不好的做法,它隐藏了一个类型是指针的事实。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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