简体   繁体   English

将unsigned char *强制转换为long

[英]Casting unsigned char* to long

What does the following expression mean? 以下表达式是什么意思?

unsigned char *res = malloc(5);

Now I cast res : 现在我投放res

(long)res  

What does this casting mean? 这个转换是什么意思?

Using that value will interpret the address to which res points (which is just a number anyway) as a long. 使用该值将把res指向的地址(无论如何只是一个数字)解释为一个长整数。

It will work most of the time but it's not completely okay (depends a lot on how you're using it). 它在大多数时候都可以使用,但是并不完全可以(很大程度上取决于您的使用方式)。 For example if you simply want to print it, you can get away with 例如,如果您只想打印它,则可以

printf("%p", res);

As a rule of thumb: treat any cast with suspicion . 根据经验: 对任何演员表都应加怀疑

不读取分配的内存,您只是将指向该内存的指针强制转换为long。

This doesn't directly answer your question but is a useful bit of information that is more-or-less relevant to your siutation. 这并不能直接回答您的问题,而是有用的信息,与您的选择或多或少相关。

A cast from a pointer type to an integer type is implementation defined (that means the implementation decides what happens when you cast a pointer to an integer). 从指针类型到整数类型的转换是实现定义的(这意味着实现决定了当您将指针转换为整数时会发生什么)。 C99 implementations that do support some type of reversible conversion should also provide two types found in <stdint.h> specifically for converting pointers to integers, namely uintptr_t and intptr_t . 确实支持某种可逆转换的C99实现也应提供在<stdint.h>找到的两种类型,专门用于将指针转换为整数,即uintptr_tintptr_t If your implementation provides these two types, then you can safely convert a pointer to these types and back to the original pointer type. 如果您的实现提供了这两种类型,则可以安全地将指针转换为这两种类型,然后再转换回原始指针类型。

Since these types are implementation defined, you will need to check your implementations documentation for what the underlying types are. 由于这些类型是实现定义的,因此您需要检查实现文档以了解基础类型是什么。

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

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