I'm reading the section on array arithmetic in K&R and came across something curious. I posted the whole paragraph for context, but I'm mainly focused on the bold part.
If p and q point to members of the same array, then relations like ==, !=, <, >=, etc., work properly. For example, p < q is true if p points to an earlier member of the array than q does. Any pointer can be meaningfully compared for equality or inequality with zero. But the behavior is undefined for arithmetic or comparisons with pointers that do not point to members of the same array. (There is one exception: the address of the first element past the end of an array can be used in pointer arithmetic.)
What is the reason for this exception? Is an extra piece of memory allocated to the end of any array when their size is defined? If so, for what purpose? Is it to end the array with a null character?
Advertisements. A pointer in c is an address, which is a numeric value. Therefore, you can perform arithmetic operations on a pointer just as you can on a numeric value. There are four arithmetic operators that can be used on pointers: ++, --, +, and -
When a pointer is incremented, it actually increments by the number equal to the size of the data type for which it is a pointer. For Example: If an integer pointer that stores address 1000 is incremented, then it will increment by 2(size of an int) and the new address it will points to 1002.
Yes, you need to do it in a loop. C does not provide operators for manipulating the entire array at once.
There's no extra memory allocated at the end of the array. It just says that you can you the address marked with 'End' below in pointer arithmetic. Begin points to the first element of the array. End points to the first element past the end of the array.
-----------------
| | | | |
-----------------
^ ^
Begin End
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With