Demonstrating the Relationship Between Pointers and Built-In Arrays

Figure 8.17 uses the four notations discussed in this section for referring to built-in array elements—array subscript notation, pointer/offset notation with the built-in array’s name as a pointer, pointer subscript notation and pointer/offset notation with a pointer—to accomplish the same task, namely displaying the four elements of the built-in array of ints named b.


 1   // Fig. 8.17: fig08_17.cpp
 2   // Using subscripting and pointer notations with built-in arrays.
 3   #include <iostream>
 4   using namespace std;
 5
 6   int main()
 7   {
 8      int b[] = { 10, 20, 30, 40 }; // create 4-element built-in array b
 9      int *bPtr = b; // set bPtr to point to built-in array b
10
11      // output built-in array b using array subscript notation
12      cout << "Array b displayed with: Array subscript notation ";
13
14      for ( size_t i = 0; i < 4; ++i )
15         cout << "b[" << i << "] = " << b[ i ] << ' ';
16
17      // output built-in array b using array name and pointer/offset notation
18      cout << " Pointer/offset notation where "
19         << "the pointer is the array name ";
20
21      for ( size_t offset1 = 0; offset1 < 4; ++offset1 )
22         cout << "*(b + " << offset1 << ") = " << *( b + offset1 ) << ' ';
23
24      // output built-in array b using bPtr and array subscript notation
25      cout << " Pointer subscript notation ";
26
27      for ( size_t j = 0; j < 4; ++j )
28         cout << "bPtr[" << j << "] = " << bPtr[ j ] << ' ';
29
30      cout << " Pointer/offset notation ";
31
32      // output built-in array b using bPtr and pointer/offset notation
33      for ( size_t offset2 = 0; offset2 < 4; ++offset2 )
34         cout << "*(bPtr + " << offset2 << ") = "
35            << *( bPtr + offset2 ) << ' ';
36   } // end main


Array b displayed with:

Array subscript notation
b[0] = 10
b[1] = 20
b[2] = 30
b[3] = 40

Pointer/offset notation where the pointer is the array name
*(b + 0) = 10
*(b + 1) = 20
*(b + 2) = 30
*(b + 3) = 40

Pointer subscript notation
bPtr[0] = 10
bPtr[1] = 20
bPtr[2] = 30
bPtr[3] = 40

Pointer/offset notation
*(bPtr + 0) = 10
*(bPtr + 1) = 20
*(bPtr + 2) = 30
*(bPtr + 3) = 40


Fig. 8.17. Using subscripting and pointer notations with built-in arrays.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset