Pointer Arithmetic By Anand George
Pointer types Classification based on the type of data it points Types of pointers Pointer to Data Pointers to functions ( code ) All pointers are of same size 32 bit in a 32 bit OS respective of what type it is.
Pointers to data Different types int * char * float* ACustomStructure* All 32 bit size.. Then what is the difference?
Difference is.. The number of locations the pointer jumps when you add 1 ( or any number for that matter) to the pointer variable. The pointer arithmetic is counter intuitive ( some time you get 1+1 = 2, some times 3, 4 like that ) and depends on the type of data.
What does that mean? Suppose int *ptr = 100; Now the address inside variable ptr = 100; now what is ptr + 1 in a 32 bit OS? intuitive answer is 101 but actual answer is 104 ( assuming int is 4 byte )
What is the reason? by the statement ptr+1 we are telling the compiler “hey compiler I'm already pointing to an integer (int *ptr ) and now I want to point to the NEXT INTEGER ( ptr+1 )” and NOT the next memory location. Next integer is 4 bytes away so compiler has to add 4 instead of 1 to go to NEXT integer.
Demo #include <stdio.h> void main() { } int *ptrA = (int*)100; int *ptrResult = ptrA + 1; printf("ptrA = %d, ptrResult = %d ", ptrA, ptrResult ); }
Houses in a street
Jump is equal to sizeof ( data type) char* jump is 1 int* jump is 4 sizeof operator pointer arithmetic has only – and + no division, multiplication or any other operation.
Demo Allocating a chunk and accessing it with pointer arithmetic. Using different types of pointer. char, int ,short Using * to dereference the pointer variable. sizeof operator
Summary Pointer types based on size of data it points to int* char* Difference between the pointer types is the amount it jumps when arithmetic is done. sizeof operator.
Thank You