Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting int to int* then back to int

Tags:

c

gcc

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?

like image 349
Hamza Yerlikaya Avatar asked Feb 11 '11 21:02

Hamza Yerlikaya


People also ask

Can you cast a pointer to an int?

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.

Can you return an int as a string?

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.

Is typecast from void * into int * Possible?

void *p = malloc(n * sizeof(int)); int *q = (int *) p; int *q = p; // implicit type cast from void * to int * is allowed!


3 Answers

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.

like image 199
Joseph Stine Avatar answered Sep 17 '22 02:09

Joseph Stine


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;
like image 30
SoapBox Avatar answered Sep 21 '22 02:09

SoapBox


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.

like image 23
Mark Loeser Avatar answered Sep 20 '22 02:09

Mark Loeser