struct – setup and memory locations

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 :).

One thought on “struct – setup and memory locations”

  1. Actually a class is very similar, you are able to pull back the internal structure in the same way (the struct is a public interface, whereas a class is like a struct but defaults to private and has public, private,protected)

    So if you had a class like

    class myclasstest {
    public:
        myclasstest(int p, int s) { x = p; y = s;}
     
    private:
        int x;
        int y;
    };

    and had some code like this

        myclasstest classtest(2,3);
        int value;
        memcpy(&value, (int*)&classtest, sizeof(int));
        cout << "the first value within a class is " << value << endl;
        memcpy(&value, ((int*)&classtest)+1, sizeof(int));
        cout << "the second value within a class is " << value << endl;

    the output would be

    the first value within a class is 2
    the second value within a class is 3

Leave a Reply

Your email address will not be published. Required fields are marked *