### Accessing arrays using pointer arithmetic

• Using pointer arithmetic to access array elements

• Using pointer arithmetic to access array elements

• Because the expression:

 ``` p + x ```

evaluates to:

 the address of the xth array element following the array element that is pointed to by p !!

• Therefore: the expression:

 ``` *( p + x ) ```

evaluates to:

 the variable that is the xth array element following the array element that is pointed to by p !!

Example:

Explanation:

• If p = &a[0], then:

 ``` *p is an alias for a[0] *(p+0) is also an alias for a[0] *(p+1) is also an alias for a[1] *(p+2) is also an alias for a[2] ```

• Example C program:

 ``` int main(int argc, char *argv[]) { int a[10] = { 11, 22, 33, 44, 55, 66, 77, 88, 99, 777 }; int *p; p = &a[0]; // p points to variable a[0] printf("*p = %d, a[%d] = %d\n", *p, 0, a[0] ); printf("*(p + 1) = %d, a[%d] = %d\n", *(p+1), 1, a[1] ); printf("*(p + 2) = %d, a[%d] = %d\n", *(p+2), 2, a[2] ); printf("*(p + 3) = %d, a[%d] = %d\n", *(p+3), 3, a[3] ); } ```

Output:

 ``` *p = 11, a[0] = 11 *(p + 1) = 22, a[1] = 22 *(p + 2) = 33, a[2] = 33 *(p + 3) = 44, a[3] = 44 ```

• Example Program: (Demo above code)

How to run the program:

 Right click on link(s) and save in a scratch directory To compile:   gcc pointer-arithm2.c To run:          ./a.out