Factor
Factor

Reputation: 31

Need help understanding pointer variable assignments

I'm not good at advanced C++ scripts. I have tried to find out more about the following variable assignments without success. Please explain them or give me a source to study similar statements.

rand_seed = *(int*)input_buffer_ptr;
moving_input_ptr = (BYTE*)((int*)input_buffer_ptr + 1);

Upvotes: 3

Views: 82

Answers (1)

Yevhen Kuzmovych
Yevhen Kuzmovych

Reputation: 12130

(Considering that int is 4 bytes)

Imagine RAM as a long line of bytes (because it is):

RAM: .... [8bit][8bit][8bit][8bit][8bit][8bit][8bit][8bit][8bit][8bit] ....

and SOME_TYPE* as the pointer on some byte:

.... [8bit][8bit][8bit][8bit][8bit][8bit][8bit][8bit][8bit][8bit] ....
           ^
      input_buffer_ptr

int* means that you treat data under this pointer as integer (number of size 4 bytes)

So if you have pointer SOME_TYPE* input_buffer_ptr

(int*)input_buffer_ptr; // casts this pointer to int*, 
     //so now you treat data under this pointer as 4 bytes integer

then:

*(int*)input_buffer_ptr; // operator * before pointer gets data under 
          //that pointer, in this case, integer (4 bytes).

So rand_seed is integer and has value:

.... [8bit][8bit][8bit][8bit][8bit][8bit][8bit][8bit][8bit][8bit] ....
           |      random_seed     |

Then:

     (int*)input_buffer_ptr + 1
//    ^                     ^
// casting to int*      moving pointer to size of int (4 bytes)

So:

.... [8bit][8bit][8bit][8bit][8bit][8bit][8bit][8bit][8bit][8bit] ....
                                   ^
                         ((int*)input_buffer_ptr + 1)

And then:

 (BYTE*)((int*)input_buffer_ptr + 1);
// ^
// casting pointer to BYTE*, so it points to the same place
// but now treated as one byte pointer.

so if you try this:

BYTE a = *(BYTE*)((int*)input_buffer_ptr + 1);

you will get one byte variable with value:

.... [8bit][8bit][8bit][8bit][8bit][8bit][8bit][8bit][8bit][8bit] ....
                                   |  a  |

Upvotes: 2

Related Questions