Hardware Reference
In-Depth Information
if (a[j]
.
a[j
1
1])
swap (&a[j], &a[j
1
1]);
}
void swap (int *px, int *py)
{
int temp;
temp
5
*px;
*px
5
*py;
*py
5
temp;
}
▲
In C, there is a strong relationship between pointers and arrays. Any operation that can
be achieved by array subscripting can also be done with pointers. The pointer version will in
general be faster but somewhat harder to understand. For example,
int ax[20];
defi nes an array
ax
of 20 integral numbers. The notation
ax
[i] refers to the
i
th element of the
array. If
ip
is a pointer to an integer, declared as
int *ip;
then the assignment
ip
5
&ax[0];
makes
ip
contain the address of
ax
[0]. Now the statement
x
5
*ip;
will copy the contents of
ax
[0] into
x
. If
ip
points to
ax
[0], then
ip
1
1
points to
ax
[1], and
ip
1
i
points to
ax
[i], and so on.
An array name can be used as an argument to a function, thus permitting the entire array to
be passed to the function. To pass an array to a function, the array name must appear by itself,
without brackets or subscripts, as an actual argument within the function call. When declaring a
one-dimensional array as a formal argument, the array name is written with a pair of empty square
brackets. The size of the array is not specified within the formal argument declaration. If the array
is two-dimensional, then there should be two pairs of empty brackets following the array name.
The following program outline illustrates the passing of an array from the main portion of
the program to a function:
int average (int n, int arr[]);
void main ( )
{
int n, avg;
/* variable declaration */
int arr[50];
/* array definition */
. . .
avg
5
average(n, arr);
/* function call */
. . .
}
Search WWH ::
Custom Search