box-o-sand/ex15.c

54 lines
1.2 KiB
C
Raw Normal View History

2011-09-18 17:30:03 +00:00
#include <stdio.h>
int main(int argc, char *argv[])
{
// create two arrays we care about
2011-09-18 17:30:03 +00:00
int ages[] = {23, 43, 12, 89, 2};
char *names[] = {
"Alan", "Frank",
"Mary", "John", "Lisa"
};
// safely get the size of ages
2011-09-18 17:30:03 +00:00
int count = sizeof(ages) / sizeof(int);
int i = 0;
// first way using indexing
2011-09-18 17:30:03 +00:00
for(i = 0; i < count; i++) {
printf("%s has %d years alive.\n",
names[i], ages[i]);
}
printf("---\n");
// setup the pointers to the start of the arrays
2011-09-19 17:19:28 +00:00
int *cur_age = ages;
2011-09-18 17:30:03 +00:00
char **cur_name = names;
// second way using pointers
2011-09-18 17:30:03 +00:00
for(i = 0; i < count; i++) {
printf("%s is %d years old.\n",
*(cur_name+i), *(cur_age+i));
}
printf("---\n");
// third way, pointers are just arrays
2011-09-18 17:30:03 +00:00
for(i = 0; i < count; i++) {
printf("%s is %d years old again.\n",
cur_name[i], cur_age[i]);
}
printf("---\n");
// fourth way with pointers in a stupid complex way
2011-09-18 17:30:03 +00:00
for(cur_name = names, cur_age = ages;
(cur_age - ages) < count;
cur_name++, cur_age++)
{
printf("%s lived %d years so far.\n",
*cur_name, *cur_age);
}
return 0;
}