C Pointer to an Array

C Arrays

You can skip this chapter for now, and come back to study it after understanding the concept of C pointers.

If you have some understanding of pointers in C, you can start studying this chapter.

The array name itself is a constant pointer, meaning its value cannot be changed; once determined, it cannot point to anywhere else.

Therefore, in the following declaration:

double balance[50];

balance.passign tobalancethe address of the first element:

double *p;
double balance[10];

p = balance;

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

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

Example

#include <stdio.h> int main () { /*Integer array with 5 elements*/ double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0}; double *p; int i; p = balance; /*Output the value of each element in the array*/ printf( "Array values using pointers\n"); for ( i = 0; i < 5; i++ ) { printf("*(p + %d) : %f\n", i, *(p + i) ); } printf( "Array value using balance as its address\n"); for ( i = 0; i < 5; i++ ) { printf("*(balance + %d) : %f\n", i, *(balance + i) ); } return 0; }

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

使用指针的数组值
*(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 above example, p is a pointer to double, which means it can store the address of a double type variable. Once we have the address in p,*pwill give the value stored at the corresponding address in p, as demonstrated in the above example.

C Arrays

other extensions