Reputation: 919
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
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
Reputation: 181077
The allocated memory is not read, you're just casting the pointer to the memory to a long.
Upvotes: 2
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