mary
mary

Reputation: 919

Casting unsigned char* to long

What does the following expression mean?

unsigned char *res = malloc(5);

Now I cast res:

(long)res  

What does this casting mean?

Upvotes: 1

Views: 1544

Answers (3)

dreamlax
dreamlax

Reputation: 95365

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. 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.

Upvotes: 0

Joachim Isaksson
Joachim Isaksson

Reputation: 181077

The allocated memory is not read, you're just casting the pointer to the memory to a long.

Upvotes: 2

cnicutar
cnicutar

Reputation: 182734

Using that value will interpret the address to which res points (which is just a number anyway) as a long.

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.

Upvotes: 4

Related Questions