box-o-sand/ex15.c

90 lines
2.0 KiB
C
Raw Normal View History

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