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

KWMelvin kwmelvin at intrex.net
Tue Nov 26 12:44:37 EST 2002


#include <stdio.h>
#define SIZE 5
int main(void)
{
  int array[SIZE]; /* declare an integer array        */
  int *ptr;        /* declare a pointer to an integer */
  int i;           /* use with the for statement      */
	
  ptr = &array[0]; /* assign the address of array[0] to ptr     */
  for (i = 0; i < SIZE; i++) {
    *ptr++ = 0;    /* use a pointer to initialize array to zero */
    printf("%d ", array[i]);  /* segfaults with array[*ptr]     */
  }
  printf("\n");

	ptr = &array[0]; /* assign the address of array[0] to ptr     */
  for (i = 0; i < SIZE; i++) {
    *(ptr+1) = 0;  /* use a pointer to initialize array to zero */
    printf("%d ", array[*ptr]);
  }
  printf("\n");

	return 0;
}

On Tue, Nov 26, 2002 at 10:33:29AM -0500, Lorne Gutz wrote:
> >
> > When you have set ptr = array[0], all you need to do is ptr++ and
> > you will be pointing at array[1].
> >
> > cheers
> > Lorne

Hello Lorne,

Here's some questions for you: The C program  above segfaults (<- is
this a word?) when I put array[*ptr] in place of array[i] on line 12.
Why? Notice what is going on in line 19, where I've replaced array[i]
with array[*ptr], but have  *(ptr+1) = 0; in line 18, as opposed to
*ptr++ = 0;  in line 11.

My command-line compile is:  gcc progname.c -o progname

I changed  ptr = array;  to  ptr = &array[0];  as you suggested, but
that didn't make any difference on my computer. It does make it easier
to read and understand, so I will use that from now on.

Cheers!
--
K




More information about the Courses mailing list