When you setup a struct within c++, it is kinder like having a array of data and if you want to you can access the internal parts by using some memory pointer location fun!.
Lets say that you have a struct of
struct intvalue { int a; int b; }; |
Just to say that since I am using int(eger) values so that is what I am incrementing by in the pointer arithmetic which is why I am casting the pointer to a integer value.
So lets say that we create a variable of intvalue and setup the values as below
intvalue testvalue; testvalue.a = 4; testvalue.b = 5; |
We can then pull out the value of a or b, but using memcpy and just outputting to a int(eger) variable as below, the key is the ((int*)&testvalue)+1, this will first convert the testvalue variable to a pointer to memory location and then (int*) casts that pointer to a int pointer, because internally that is what it is, and then just add 1 to it, which points to the second value ( in this case the value of b which is 5)
int avalue; // convert to a int pointer type and then add one to it (to the next array element as such). memcpy(&avalue, ((int*)&testvalue)+1,sizeof(int)); cout << "a value (or is it the b value :) ) " << avalue << endl; |
The output would be
a value (or is it the b value :) ) 5 |
because I am pointing to the second value which is b and thus 5 :).
Of course if you just wanted the value of first int (the value of a in this case) you do not add the 1 to the memory location, for example
memcpy(&avalue, ((int*)&testvalue),sizeof(int)); |
this time I am just converting the testvalue (casting) to a int pointer and thus pointing to the start of the struct and that is where the int a variable is living :).