Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C Pointers to Arrays

C Pointers to Arrays

C Arrays C Arrays

You can skip this chapter first, and come back to learn its content after you understand the concept of C pointers.

If you have some understanding of the concept of pointers in C, then you can begin studying this chapter.

The array name itself is a constant pointer, which means its value cannot be changed; once determined, it cannot point elsewhere.

Therefore, in the following declaration:



double balance[50];

balance is a pointer to &balance[0], that is, the address of the first element of the array balance. Therefore, the following program fragment p to balance 's first element address:



double *p;

double balance[10];



p = balance;

It is legal to use an array name as a constant pointer, and vice versa. Therefore, *(balance + 4) is a legal way to access the data of balance[4].

Once you store the address of the first element in p, you can use p, (p+1), *(p+2), etc. to access array elements. The example below demonstrates the concepts discussed above:

Example

#include

<

stdio.h

int

main

(

)

{

/*

An integer array with 5 elements

*/

double

balance

[

5

]

=

{

1000

.0

,

2

.0

,

3

.4

,

17

.0

,

50

.0

}

;

double

p

;

int

i

;

p

=

balance

;

/*

Print the value of each element in the array

*/

printf

(

"

Array values using pointer

\

n

"

)

;

for

(

i

=

0

;

i

<

5

;

i

++

)

{

printf

(

"

*(p + %d) : %f

\

n

"

,

i

, *

(

p

i

)

)

;

}

printf

(

"

Using balance as an address to access array values

\

n

"

)

;

for

(

i

=

0

;

i

<

5

;

i

++

)

{

printf

(

"

*(balance + %d) : %f

\

n

"

,

i

, *

(

balance

i

)

)

;

}

return

0

;

}

When the code above is compiled and executed, it produces the following result:



使用指针的数组值

*(p + 0) : 1000.000000

*(p + 1) : 2.000000

*(p + 2) : 3.400000

*(p + 3) : 17.000000

*(p + 4) : 50.000000

使用 balance 作为地址的数组值

*(balance + 0) : 1000.000000

*(balance + 1) : 2.000000

*(balance + 2) : 3.400000

*(balance + 3) : 17.000000

*(balance + 4) : 50.000000

In the example above, p is a pointer to double, which means it can store a variable of type double. Once we have the address in p, *p will give the value stored at the corresponding address in p, as demonstrated in the example above.

C Arrays C Arrays