Pointer Arithmetic

Since pointers are declared of a specific data type they are allocated a specific amount of memory according to that data type.

 

Arithmetic is carried out based upon the units of allocated memory, by data type.

 

For instance, a char pointer is allocated one byte, an int pointer is allocated four bytes, arithmetic carried out upon these would be by the size of the data type; accordingly, a single increment of an int pointer would increase the pointed to address by four bytes, that is, the next integer.

 

Similarly, incrementing a char by one would increase the pointed to address by one byte:

Compile & Run:

charArr[0] contains: V at address location: 0x28fef1
charArr[1] contains: a at address location: 0x28fef2
charArr[2] contains: n at address location: 0x28fef3
charArr[3] contains: e at address location: 0x28fef4
charArr[4] contains: s at address location: 0x28fef5
charArr[5] contains: s at address location: 0x28fef6
charArr[6] contains: a at address location: 0x28fef7

 

 

*Note: the address is having to be type cast (on line  12) due to cout overloading the << operator

source

Leave a Reply