Latest web development tutorials

C ++ pointer to an array

C ++ Array C ++ Array

You can skip this chapter, and so understand the concept of C ++ pointers after, come to learn in this chapter.

If you understand the concept of C ++ pointers, 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 <iostream>
using namespace std;
 
int main ()
{
   // 带有 5 个元素的整型数组
   double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
   double *p;

   p = balance;
 
   // 输出数组中每个元素的值
   cout << "使用指针的数组值 " << endl; 
   for ( int i = 0; i < 5; i++ )
   {
       cout << "*(p + " << i << ") : ";
       cout << *(p + i) << endl;
   }

   cout << "使用 balance 作为地址的数组值 " << endl;
   for ( int i = 0; i < 5; i++ )
   {
       cout << "*(balance + " << i << ") : ";
       cout << *(balance + i) << endl;
   }
 
   return 0;
}



#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
* (P + 1): 2
* (P + 2): 3.4
* (P + 3): 17
* (P + 4): 50
Use balance value as an array address * (balance + 0): 1000
* (Balance + 1): 2
* (Balance + 2): 3.4
* (Balance + 3): 17
* (Balance + 4): 50

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