I. Differences between Reference and pointer
Although both reference and pointer can indirectly access another value, there are two important differences between them. The first difference is that the reference always points to an object: it is wrong to define the reference without initialization. The second important difference is the difference in the assignment behavior: assigning a value to a reference modifies the value of the object associated with the reference, rather than associating the reference with another object. Once the reference is initialized, it always points to the same specific object (that is why the reference must be initialized at definition ). Consider the following two sections. The first program section assigns a pointer to another pointer:
int ival = 1024, ival2 = 2048; int *pi = &ival, *pi2 = &ival2; pi = pi2; // pi now points to ival2
After the assignment is complete, the value of the ival object pointed to by pi remains unchanged. The assignment operation modifies the value of the pi pointer so that it points to another object. Now, consider another similar program and assign values using two references:
int &ri = ival, &ri2 = ival2; ri = ri2; // assigns ival2 to ival
This assignment operation modifies the ival object referenced by ri, not the reference itself. After the assignment, the two references still point to the originally associated objects, and the values of these two objects are equal.
II
int *ip[4]; // array of pointers to intint (*ip)[4]; // pointer to an array of 4 ints
Three typedef simplifies pointer to multi-dimensional array
The typedef type definition makes it easier to read, write, and understand the pointer to a multi-dimensional array element. The following program uses typedef to define a new type name for the ia element type:
int ia[3][4]; // array of size 3, each element is an array of ints of size 4 int (*ip)[4] = ia; // ip points to an array of 4 ints ip = &ia[2]; // ia[2] is an array of 4 intstypedef int int_array[4]; int_array *ip = ia;
You can use the typedef type to output ia elements:
for (int_array *p = ia; p != ia + 3; ++p) for (int *q = *p; q != *p + 4; ++q) cout << *q << endl;
The for loop of the outer layer first initializes p to the first internal array of ia, and then loops until all the three data rows of ia are processed. + P adds 1 to p, which is equivalent to moving the pointer to the next row of ia (for example, the next element ).