90 lines
2.0 KiB
C
90 lines
2.0 KiB
C
#include <stdio.h>
|
|
|
|
void print_with_array_indexing(int count, char **names, int *ages)
|
|
{
|
|
int i = 0;
|
|
|
|
// first way using indexing
|
|
while(i < count) {
|
|
printf("%s has %d years alive.\n",
|
|
names[i], ages[i]);
|
|
i++;
|
|
}
|
|
|
|
printf("---\n");
|
|
}
|
|
|
|
void print_with_pointer_arithmetic(int count, char **names, int *ages)
|
|
{
|
|
int i = 0;
|
|
// setup the pointers to the start of the arrays
|
|
int *cur_age = ages;
|
|
char **cur_name = names;
|
|
|
|
// second way using pointers
|
|
while(i < count) {
|
|
printf("%s is %d years old.\n",
|
|
*(cur_name+i), *(cur_age+i));
|
|
i++;
|
|
}
|
|
|
|
printf("---\n");
|
|
}
|
|
|
|
void print_with_pointers_as_arrays(int count, char **names, int *ages)
|
|
{
|
|
int i = 0;
|
|
int *cur_age = ages;
|
|
char **cur_name = names;
|
|
// third way, pointers are just arrays
|
|
while(i < count) {
|
|
printf("%s is %d years old again.\n",
|
|
cur_name[i], cur_age[i]);
|
|
i++;
|
|
}
|
|
|
|
printf("---\n");
|
|
|
|
}
|
|
|
|
void print_in_stupidly_complex_way(int count, char **names, int *ages)
|
|
{
|
|
int *cur_age = ages;
|
|
char **cur_name = names;
|
|
|
|
// fourth way with pointers in a stupid complex way
|
|
while((cur_age - ages) < count) {
|
|
printf("%s lived %d years so far.\n",
|
|
*cur_name++, *cur_age++);
|
|
}
|
|
|
|
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++) {
|
|
printf("argument %d is '%s' (address = %p)\n", i, *arg, (void *)arg);
|
|
arg++;
|
|
}
|
|
|
|
return 0;
|
|
}
|