Generating a Pointer to an Array. McGraw-Hill The Complete Reference Fourth Edition
Quảng cáo
Quảng cáo
92
C + + : T h e C o m p l e t e R e f e r e n c e
Generating a Pointer to an Array
You can generate a pointer to the first element of an array by simply specifying the array name, without any index. For example, given int sample[10]; you can generate a pointer to the first element by using the name sample. Thus, the following program fragment assigns p the address of the first element of sample: int *p; int sample[10]; p = sample;
You can also specify the address of the first element of an array using the & operator.
For example, sample and &sample[0] both produce the same results. However, in professionally written C/C++ code, you will almost never see &sample[0].
Passing Single-Dimension Arrays to Functions
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 */
{
C h a p t e r 4 : A r r a y s a n d N u l l - T e r m i n a t e d S t r i n g s
93
}
.
.
.
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.
Tải xuống
Quảng cáo