home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
The C Users' Group Library 1994 August
/
wc-cdrom-cusersgrouplibrary-1994-08.iso
/
listings
/
v_11_09
/
1109110b
< prev
next >
Wrap
Text File
|
1993-07-13
|
1KB
|
59 lines
/* 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
*/