39. Pointers and Arrays 2

Suppose that a is an int array of size 10.
If pa is a pointer to an integer, i.e.,
int *pa;
then the assignment
pa = &a[0];
sets pa to point to element zero of a.
When does x = *pa; make sense – what does the type of x have to be? What does it do?

If pa points to an element of an array, then (by definition) pa + 1 points to the next element.
In general, pa + i points to the ith element after the element pointed to by pa.
Example.
int a[4] = { 0, 1, 2, 3 };
int *p;
p = &a[0];
printf( "%d\n", *(p + 2)); // prints 2
scanf( "%d", p + 3 ); // take input in a[3]
printf( "You typed: %d\n", a[3] );

More on pointers and arrays

In fact, the name of an array is a synonym for the address of the initial element.
As an example, when we have the declarations int a[10]; int *pa;
&a[0] is the same as a, and thus-
pa = &a[0];
is the same as
pa = a;.

For any expression b of type int *, b[i] can always be written as *(b + i), and vice-versa.

For example, given the above declarations:
a[i] and *(a + i) are equivalent
pa[i] and *(pa + i) are equivalent

Even more on pointers and arrays

Note that an array name (like a assuming the above declarations) is not a variable, so statements like
a = pa; and a++; are illegal. (You also don’t want to form the expression &a.)

Practice: Pointers and Arrays

void main() {
int a[4] = { 0, 1, 2, 3 };
int *pa;
pa = a + 1;
printf( "%d\n", *pa ); // prints 1
printf( "%d\n", pa[2] ); // prints 3
pa++;
printf( "%d\n", pa[0] ); // prints 2
scanf( "%d", pa + 1 ); // input at a[3]
printf( "You typed: %d\n", a[3] ); // prints 3
}

Post by J.siam
Ref Herbert Schildt

1 comment:

  1. This article was very useful keep up the good work……really helpful article….thanx

    ReplyDelete

free counters