[Courses] [C] Beginner's Lesson 12: another answer to Exercise 1 (Simple Pointers)

KWMelvin kwmelvin at intrex.net
Sun Nov 24 07:48:02 EST 2002


Greetings,

I've modified ptr-init-array.c (21 Nov) to come up with another
answer, using pointer arithmetic.  In ptr-init-array2.c I've used
my first pointer answer to initialize each array element to its element
number, and used pointer arithmetic to initialize each array element
to zero. As you can see, I'm working my way (slowly) through the
Jensen pointer tutorial. 8^D

Happy Programming!
--
K

/*******************************************************
** ptr-init-array2.c -- modified from: ptr-init-array.c
** another answer to Question 1, Lesson 12 
** 24 Nov 2002 -- K
*******************************************************/
#include <stdio.h>
#define SIZE 10
int main(void)
{
  int array[SIZE]; /* an array of integers        */
  int i;           /* an integer for use with for */
  int *ptr;        /* a pointer to an integer     */

  /* here each element is initialized to the element number */
  for (i = 0; i < SIZE; i++)
  {
      ptr = &i;                  /* ptr gets address of i */
      array[*ptr] = i;           /* *ptr gets value at &i */
      printf("%3d", array[i]);
  }
  printf("\n"); 
  
  /* initialize each array element to zero using pointer arithmetic */
  ptr = &array[0];           /* point ptr to first element of array */
  for (i = 0; i < SIZE; i++)
  {
    array[*(ptr + 1)] = 0;     /* use pointer arithmetic to get to  */
    printf("%3d", *(ptr + 1)); /* the next element in the array     */
  }
  printf("\n");
 
  return 0;  
}
/********************************************************************/



More information about the Courses mailing list