I am missing something obvious here but consider the following,
int k = 10;
int *p = &k;
int i = (int)p;
above produces,
warning: cast from pointer to integer of different size
and following,
int k = 10;
int *p = &k;
int i = p;
causes,
warning: initialization makes integer from pointer without a cast
a bit of googling lead me to,
Converting a pointer into an integer
which advices using uintptr_t,
int k = 10;
int *p = &k;
int i = (uintptr_t)p;
above works no errors no warnings. So my question is k is an int and p is an int pointer pointing to k why do i get an error dereference p?
Any pointer type may be converted to an integer type. Except as previously specified, the result is implementation-defined. If the result cannot be represented in the integer type, the behavior is undefined. The result need not be in the range of values of any integer type.
Method 1: Using toString Method of Integer Class The Integer class has a static method that returns a String object representing the specified int parameter. The argument is converted and returned as a string instance. If the number is negative, the sign will be preserved.
void *p = malloc(n * sizeof(int)); int *q = (int *) p; int *q = p; // implicit type cast from void * to int * is allowed!
int k = 10;
int *p = &k;
int i = *p;
Note the * before p on the last line. Dereference the pointer to get the int it points to.
EDIT: I'm not very familar with uintptr_t, but I ran the code int i = (uintptr_t)p; The result that is stored into i is the memory address of k, not 10. The cast tells the compiler that you really want to turn the address into an integer (so there's no warning; because you are insisting to the compiler that you know what you are doing) but does not dereference the pointer.
You get an error because you didn't actually dereference p
, you just casted it (forcefully changed its type) from int*
. To dereference, you need to use the *
operator, like so:
int i = *p;
You aren't dereferencing the pointer, so you are assigning the address of the pointer to an int.
int i = *p;
Is what you most likely wanted.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With