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

Lorne Gutz lgutz at vistar.ca
Mon Nov 25 11:14:46 EST 2002


Add  this little bit of code below, at the end of your code 
and you will see that you have a problem.

  for (i = 0; i < SIZE; i++)
  {
     printf( "%3d", array[i] );
  }
  printf("\n");

------------------
why not just change this:

>   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");

to, what  you see below??

   for (i = 0; i < SIZE; i++, ptr++ )
   {
      *ptr  = 0;     /* use pointer arithmetic to get to  */
     printf("%3d", *ptr ); /* the next element in the array     */
   }
   printf("\n");


This does the job and is simple to understand.
    if you want to use some type of pointer math
you could use  *(ptr + i ) but not as an index.

Lorne

On Sunday 24 November 2002 06:48, KWMelvin wrote:
> /*******************************************************
> ** 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