Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer Arithmetic In C

Consider the following code fragment:

int (*p)[3];
int (*q)[3];

q = p;
q++;
printf("%d, %d\n", q, p);
printf("%d\n", q-p);

I know that pointer arithmetic is intelligent, meaning that the operation q++ advances q enough bytes ahead to point to a next 3-integers-array, so it does not surprises me that the first print is '12, 0' which means that incrementing q made it larger in 12.

But the second print does surprises me. It prints 1!
So why would it print 1 instead of 12? it just puzzles me.

like image 547
Ori Popowski Avatar asked Apr 17 '09 09:04

Ori Popowski


People also ask

What is pointer arithmetic in C?

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.

What is pointer arithmetic used for?

Pointer arithmetic provides the programmer with a single way of dealing with different types: adding and subtracting the number of elements required instead of the actual offset in bytes. (Pointer arithmetic with char * pointers uses byte offsets, because sizeof(char) is 1 by definition.)


2 Answers

Like the ++ increment operator, the - subtraction operator with pointers also takes into account the size of the objects being pointed to. Specifically, the result returned is the number of bytes difference in the pointer values divided by the size of the pointed-to object (12, in your example). So the difference is 12 bytes, divided by size 12, or 1.

like image 175
Greg Hewgill Avatar answered Oct 05 '22 08:10

Greg Hewgill


If you really want to know the difference cast each pointers to a (char*) and then to (int) and then subtract. That should give you the answer.

This code gives you the absolute value:

printf("%d\n", abs((int)((char*)q) - (int)((char*)p)));

Remember to include math.h.

Edit: As pointed out in a comment we don't need a double cast. Casting each pointerpointer to an int and then subtracting gives the same answer as the (unecessary) double casting above.

printf("%d\n", abs((int)(q) - (int)(p)));
like image 23
AnnaR Avatar answered Oct 05 '22 08:10

AnnaR