Pointers Part 2
Pointers Part 2
• Element b[3]
• Can be accessed by *(bPtr + 3)
• Where 3 is the offset. Called pointer/offset notation
• Can be accessed by bptr[3]
• Called pointer/subscript notation
• bPtr[3] same as b[3]
• Can be accessed by performing pointer arithmetic on the array
itself
*(b + 3)
• Array name itself is an address or pointer. It points to the first
element(0th element) of array.
• The arrays are accessed by pointers in same way as we access arrays
using array name.
• Consider an array b[5] and a pointer bPtr:
• bPtr[3] is same as b[3]
Example-Different notations with pointer to an array
#include<stdio.h>
int main()
{
int a[]={1,2,3,4,5};
int *p=a;
// Different notations with pointer to an array for displaying second element
// Same terminology can be used to display any element
// All will display 2 on screen
printf("\n%d",*(p+1));
printf("\n%d",*(a+1));
printf("\n%d",p[1]);
printf("\n%d",1[p]);
printf("\n%d",1[a]);
return 0;
}
Pointer to an array with pointer arithmetic
#include<stdio.h>
int main()
{
int arr[]={1,2,3,4,5};
int i;
int *p;
p=arr;
printf("\n First value is:%d",*p);
p=p+1;
printf("\n Second value is:%d",*p);
*p=45;
p=p+2;
*p=-2;
printf("\n Modified array is:");
for(i=0;i<5;i++)
{
printf("\n%d",arr[i]);//We can also write i[arr]
}
p=arr;
*(p+1)=0;
*(p-1)=1;
printf("\n Modified array is:");
for(i=0;i<5;i++)
{
printf("\n%d",*(p+i));//We can also write *(i+arr)
}
return 0;
}