adding second approach to the pointer arithmetic example
This commit is contained in:
@@ -148,7 +148,10 @@ shrink dynamically in response to the demands of the application.
|
||||
|
||||
## 4.8 Stepping through Arrays with Pointers (Array Iterators)
|
||||
|
||||
- The array code above that uses [] subscripting, can be equivalently rewritten to use pointers:
|
||||
- The array code above that uses [] subscripting, can be equivalently rewritten to use pointers. We can re-write it in two ways:
|
||||
|
||||
### 4.8.1 First Approach
|
||||
|
||||
```cpp
|
||||
const int n = 10;
|
||||
double a[n];
|
||||
@@ -178,6 +181,23 @@ square root of this value is assigned to \*p.
|
||||
|
||||
- play this [animation](https://jidongxiao.github.io/CSCI1200-DataStructures/animations/pointers/example_arrays_2/index.html).
|
||||
|
||||
### 4.8.2 Second Approach
|
||||
|
||||
The first approach uses pointer arithmetic in several places - just to demonstrate the usage of pointer arithmetic; but many students find it confusing and hard to understand. In contrast, the following approach is easier to understand, and **is the recommended way for you to use in tomorrow's lab**; use approach one only if you truly understand all the pointer arithmetics involved in approach one.
|
||||
|
||||
```cpp
|
||||
const int n = 10;
|
||||
double a[n];
|
||||
double *p;
|
||||
p = a;
|
||||
int i;
|
||||
for ( i=0; i<n; ++i ){
|
||||
*(p+i) = sqrt( (double(i) )
|
||||
};
|
||||
```
|
||||
|
||||
This second approach also "nicely mimics the subscript notation used in the for loop above, which highlights that fundamentally array subscripts are just pointer arithmetic." - comments by our mentor Eleanor Olson, :smile:.
|
||||
|
||||
## 4.9 Sorting an Array
|
||||
|
||||
- Arrays may be sorted using std::sort, just like vectors. Pointers are used in place of iterators. For example, if a is an array of doubles and there are n values in the array, then here’s how to sort the values in the array into increasing order:
|
||||
|
||||
Reference in New Issue
Block a user