Listing 2 Uses both an index and a pointer to traverse an array
/* array2.c: Traverses an array with an index and a * pointer */ #include <stdio.h> main() { int a[] = {0,1,2,3,4}; int i, *p; size_t n = sizeof a / sizeof a[0]; /* Print using array index */ for (i = 0; i < n; ++i) printf("%d ",a[i]); putchar('\n'); /* You can even swap a and i (but don't) */ for (i = 0; i < n; ++i) printf("%d ",i[a]); putchar('\n'); /* Print using a pointer */ p = a; while (p < a+n) printf("%d ",*p++); putchar('\n'); /* Using index notation with pointer is OK */ for (p = a, i = 0; i < n; ++i) printf("%d ",p[i]); putchar('\n'); /* Using pointer notation with array is OK */ for (i = 0; i < n; ++i) printf("%d ",*(a+i)); putchar('\n'); /* Print backwards using pointer */ p = a + n-1; while (p >= a) printf("%d ",*p--); putchar('\n'); /* Negative subscripts are allowed */ for (i = 0, p = a + n-1; i < n; ++i) printf("%d ",p[-i]); putchar('\n'); return 0; } /* Output 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 0 1 2 3 4 4 3 2 1 0 4 3 2 1 0 */ /* End of File */