Structure Pointer Increment/Decrement c++

I have a pointer to a structure in c++. I increment it. When I decrement the pointer it does not return to the original address. Would you please explain why it does not return to the original address when I decrement it? Your assistance is greatly appreciated.

#include    <iostream>

using namespace std;

struct  __attribute__((__packed__)) theStructure
{
    int boop;
};

int main(int argc, char *argv[])
{
    // Integer stuff
    int intArray[27];
    int *ptrMyInts;

    ptrMyInts = intArray;
    cout << " The int address: " << ptrMyInts << endl;
    
    ptrMyInts++;
    cout << " The int address: " << ptrMyInts << endl;

    ptrMyInts--;
    cout << " The int address: " << ptrMyInts << endl << endl << endl;


    // Structure stuff
    struct  theStructure    *ptrMyStructure;
    
    ptrMyStructure = new theStructure;
    cout << " The structure address: " << ptrMyStructure << endl;

    ptrMyStructure++;
    ptrMyStructure = new theStructure;
    cout << " The structure address: " << ptrMyStructure << endl;

    ptrMyStructure--;
    cout << " The structure address: " << ptrMyStructure << endl;
    
    return(0);
}

This code yields the following results:

The int address: 0xbebee52c
The int address: 0xbebee530
The int address: 0xbebee52c


The structure address: 0x1f6d460
The structure address: 0x1f6d470
The structure address: 0x1f6d46c

I'm not sure why when decremented the structure is 0x1f6d46c intstead of the original 0x1f6d460.



Read more here: https://stackoverflow.com/questions/64932970/structure-pointer-increment-decrement-c

Content Attribution

This content was originally published by Mr. Whiskers at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: