Harsh M. Shah
Harsh M. Shah

Reputation: 663

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.

Upvotes: 1

Views: 64

Answers (1)

Ajay
Ajay

Reputation: 18431

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.

Upvotes: 3

Related Questions