Pointer arithmetic is useful because it allows for large amounts of data to be stored and accessed more easily.
The relationship between arrays and pointers is that adding a sum of 'x' to a pointer reference of an array will set the pointer to
the 'x' element of that array. arr[x] = *(arr + x). This is because a pointer to an array points to the first byte that the array
occupies. By adding and in "x" to the pointer, we are adding (x * sizeOf(data)) and thus moving that number of bytes further in
memory to point at the next element in the array.
Pointer arithmetic is useful because it allows for convenient access to array-like structures in memory since it scales by the size of the target type.
The relationship between arrays and pointers is that adding a sum of "x" to a pointer reference of an array will set the pointer to
the "x" element of that array. arr[x] = *(arr + x). This is because a pointer to an array points to the first byte that the array
occupies. By adding "x" to the pointer, we are adding (x * sizeOf(data)) and thus moving that number of bytes further in
Firstly, storing the addresses as longs is necessary to find the difference in bytes. This is due to pointer arithmetic. For instance, the first three functions asked for us to
calculate the size (in bytes) of the data stored in an array. To accomplish this, we intialized one pointer to the start of the array and another to the start + 1. Since the pointers
were not casted, start + 1 was scaled up by the size of the data in the array. We then casted these pointers to longs so that when we subtacted them, we did not have our answer scaled down
...
...
@@ -27,21 +25,13 @@ by a factor of the size of data in the array. This results in the difference in
returned an answer of 1. We chose to cast these pointers to type long since type long has a size of 8 bytes which is large enough to store the entire pointer. On the other hand, a data
type, such as int, that is not 8 bytes large would not be able to properly store the pointers in only 4 bytes.
Secondly, casting these two adresses to
longs is necessary because both a long and a pointer address have 8 bytes. Thirdly, we subtract the two casted pointers to find the difference.
It is necessary for the parameters for swapInts to be pointers because the address of each int must be given in order for the function to swap their values. If the pointers were not passed,
rather it was instead just the ints, then the actual value at the address the pointers are pointing to would not change. Instead, the changes to the ints would only be reflected within the function,
and the value in memory at those specific addresses would not be any different.
If the parameters were integers, the function would not return swapped integers because there would be no addresses given to swap the values without pointers as the parameters.