Facebook
From Chunky Giraffe, 1 Year ago, written in Plain Text.
Embed
Download Paste or View Raw
Hits: 150
  1. #include <stdio.h>
  2. int main(int argc, char *argv[])
  3. {
  4.  // create two arrays we care about
  5.  int ages[] = {23, 43, 12, 89, 2};
  6.  char *names[] = {
  7.  "Alan", "Frank",
  8.  "Mary", "John", "Lisa"
  9.  };
  10.  // safely get the size of ages
  11.  int count = sizeof(ages) / sizeof(int);
  12.  int i = 0;
  13.  // first way using indexing
  14.  for(i = 0; i < count; i++) {
  15.  printf("%s has %d years alive.\n",
  16.  names[i], ages[i]);
  17.  }
  18.  printf("---\n");
  19.  // setup the pointers to the start of the arrays
  20.  int *cur_age = ages;
  21.  char **cur_name = names;
  22.  // second way using pointers
  23.  for(i = 0; i < count; i++) {
  24.  printf("%s is %d years old.\n",
  25.  *(cur_name+i), *(cur_age+i));
  26.  }
  27.  printf("---\n");
  28.  // third way, pointers are just arrays
  29.  for(i = 0; i < count; i++) {
  30.  printf("%s is %d years old again.\n",
  31.  cur_name[i], cur_age[i]);
  32.  }
  33.  printf("---\n");
  34.  // fourth way with pointers in a stupid complex way
  35.  for(cur_name = names, cur_age = ages;
  36.  for(cur_name = names, cur_age = ages;
  37.  (cur_age - ages) < count;
  38.  cur_name++, cur_age++)
  39.  {
  40.  printf("%s lived %d years so far.\n",
  41.  *cur_name, *cur_age);
  42.  }
  43.  return 0;
  44. }
  45.  

Replies to Untitled rss

Title Name Language When
Re: Untitled Red Pelican text 1 Year ago.