[Courses] Re: [C] Beginner's Lesson 12: another answer to Exercise 1 (Simple Pointers)
Lorne Gutz
lgutz at vistar.ca
Tue Nov 26 10:11:56 EST 2002
On Monday 25 November 2002 15:40, Morgon Kanter wrote:
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
>
> Your code won't work:
> > 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 */
> > }
>
> rather, try:
> array[(*ptr + i)] = 0;
> printf("%3d", (*ptr + i));
This code only works because each element of the array has been
initilized to the index. ie array[4] = 4.
Change the initilization so that each element is array[i] = 1200 +i,
and see what happens.
Look at what you have here. first ptr is set equal to the address of
array[0]. Now that element just happens to contain a zero so when
you go *ptr you have a zero, and array[*(ptr +i )] is equal to array[0];
but if you make the change I suggested above *(ptr +i) will equal
(1200 + i) , array[ (1200 +i)] is an array overrun and you will
probably get a Segmentation fault.
When you have set ptr = array[0], all you need to do is ptr++ and
you will be pointing at array[1].
cheers
Lorne
More information about the Courses
mailing list