Programming with Passion

Make the best out of everything.

Saturday, 26 March 2016

Pointers

Pointers are the variables that hold address. Pointers can point at cells of an array not only single variable. Consider this example:
int* ptr;
int a[5];
ptr = &a[2];  // &a[2] is the address of third element of a[5].
Suppose, pointer needs to point to the fourth element of an array, that is, hold address of fourth array element in above case. Since ptr points to the third element in the above example, ptr + 1 points to the fourth element. You may think that, ptr + 1 may hold the address of byte next to ptr. But it's not correct. It is because pointer ptr is a pointer to int and size of int is fixed for a operating system (size of int is 4 byte of 64-bit operating system). Hence, the address between ptr and ptr + 1 differs by 4 bytes. If pointer ptr was pointer to char then, the address between ptr and ptr + 1 would have differed by 1 byte since size of a character is 1 byte.

No comments:

Post a Comment