Sunday, September 26, 2010

Passing Single-Dimension Arrays to Functions In C/C++

In C/C++, you cannot pass an entire array as an argument to a function. You can,
however, pass to the function a pointer to an array by specifying the array's name
without an index. For example, the following program fragment passes the address of i
to func1() :
int main(void)
{
int i[10];
func1(i);
.
.
.
}
If a function receives a single-dimension array, you may declare its formal
parameter in one of three ways: as a pointer, as a sized array, or as an unsized array.
For example, to receive i, a function called func1() can be declared as void func1(int *x) /* pointer */
{
.
.
.
}
or
void func1(int x[10]) /* sized array */
{
.
.
.
}
or finally as
void func1(int x[]) /* unsized array */
{
.
.
.
}
All three declaration methods produce similar results because each tells the
compiler that an integer pointer is going to be received. The first declaration actually
uses a pointer. The second employs the standard array declaration. In the final version,
a modified version of an array declaration simply specifies that an array of type int of
some length is to be received. As you can see, the length of the array doesn't matter as
far as the function is concerned because C/C++ performs no bounds checking. In fact,
as far as the compiler is concerned,
void func1(int x[32])
{
.
.
.
}
also works because the compiler generates code that instructs func1() to receive a
pointer—it does not actually create a 32-element array.

No comments:

Post a Comment