Home > Mobile >  How to write a int* to char[]?
How to write a int* to char[]?

Time:12-12

I have

int some_var = 5;
int* ref_on_var = &a;
char arr[8];
char* to_write = reinterpret_cast<char*>(&ref_on_var);

I want to write ref_on_var to arr so i write this

for(size_t i = 0; i < sizeof(int*);   i)
{
     arr[i] = to_write[i];
}

This writes some bytes to array but when I try to get pointer back by

int* get = reinterpret_cast<int*>(arr);

I get incorrect address. So what do I do wrong?

CodePudding user response:

arr

This evaluates to a pointer to arr, that's the result of using the name of an array in a C expression.

This char buffer contains an int *, therefore this must be an int **. So:

int* get = *reinterpret_cast<int**>(arr);
  •  Tags:  
  • c
  • Related