Latest web development tutorials

C pointer to an array

C array C array

You can skip this chapter and then wait to understand the concept of C pointers, come to learn in this chapter.

If you understand the concept of pointers in C language, then you can begin to learn in this chapter. Array name is a constant pointer pointing to the first element of the array. Therefore, in the following statement:

double balance[50];

balance is a point & balance [0] pointer that address the first element of the array of the balance.Therefore, the following program fragmentp assigned to the first element of balancein the address:

double *p;
double balance[10];

p = balance;

Use as a constant pointer array name is legitimate, and vice versa. Therefore, * (balance + 4) is a balance [4] legitimate way to access the data.

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

#include <stdio.h>

int main ()
{
   /* 带有 5 个元素的整型数组 */
   double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
   double *p;
   int i;

   p = balance;
 
   /* 输出数组中每个元素的值 */
   printf( "使用指针的数组值\n");
   for ( i = 0; i < 5; i++ )
   {
       printf("*(p + %d) : %f\n",  i, *(p + i) );
   }

   printf( "使用 balance 作为地址的数组值\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:

Using the pointer array value * (p + 0): 1000.000000
* (P + 1): 2.000000
* (P + 2): 3.400000
* (P + 3): 17.000000
* (P + 4): 50.000000
Use balance value as an array address * (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 a pointer of type double, which means that it can be stored in a variable of type double. Once we have the addressp, * p value of p will be given the corresponding memory address, as demonstrated in the above examples.

C array C array