Incrementing pointer
Lets look at a simple code snippet
#include <stdio.h>
int main()
{
int arr[3]={1,2,3} , *ptr;
ptr = arr; //array name is its base address
printf("Base address of array = %p",ptr);
ptr = ptr + 1;
printf("\nAddress after incr = %p",ptr);
return 0;
}
O/p
Base address of array = 0xbfa13b04 Address after incr = 0xbfa13b08
As ptr is an integer pointer , ptr = ptr + 1 ,increments ptr by 4 bytes and not 1 byte.
Decrementing pointer
In the above code just change ptr=ptr+1 to ptr=ptr-1
Subtraction of 2 pointers
ptr=ptr + 1 - ptr + ptr;
printf("%d",*ptr);
ptr is pointing to the 1st element of arr i.e 2 and so *ptr prints 2.
Addition of 2 pointers
It is not allowed.But you can have an integer and pointer as 2 operands for + operator. (i.e ptr + 1 is allowed as seen previously).
Multiplication and division
These operators can’t have 2 pointers as their operands and also they can’t have an integer and pointer as their operands. ( ptr = ptr * 1 and ptr = ptr/1 is also not allowed)
No comments:
Post a Comment