Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C pointer arithmetic for arrays

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?

like image 628
ericgrosse Avatar asked Jun 18 '13 15:06

ericgrosse


People also ask

What is pointer arithmetic in C?

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 -

What is pointer arithmetic in C with example?

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.

Can we perform arithmetic operations on array in C?

Yes, you need to do it in a loop. C does not provide operators for manipulating the entire array at once.


1 Answers

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
like image 117
MvdD Avatar answered Oct 01 '22 20:10

MvdD