Search code examples
c++pointerspointer-arithmetic

How are pointers actually made to increment by the type their type


How are pointers made to increment by their type. For example if we have

int *ptr;       
ptr++;   //would point to the next integer i.e. it would increment ptr by 4bytes in 32 bit system

I wanted to know that how is this done internally.


Solution

  • The compiler compiling the code knows the base type of the pointer, and it puts the code to increment pointer (offset) appropriately. For example:

    int* p = new int[10];
    *(p+2) = 100;
    

    The second line will be like:

    p + sizeof(int) * 2 ... // Not C/C++
    

    And, similary:

    p++;
    

    Would mean:

    p = p + sizeof(int); // Not C/C++
    

    If type of p is something else (like float or some structure), the calculations would be performed appropriately. There is no magic. Types are compile time defined - a type of variable don't change at runtime, hence the calculations.