Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C pointer arithmetic

Given this code:

int *p, *q;

p = (int *) 1000;
q = (int *) 2000;

What is q - p and how?

like image 449
NLV Avatar asked Jan 22 '10 13:01

NLV


3 Answers

It's actually undefined, according to the standard. Pointer arithmetic is not guaranteed to work unless the pointers are both pointing to either an element in, or just beyond, the same array.

The relevant section of the standard is 6.5.6:9 (n1362 draft of c1x but this hasn't changed since c99) which states:

When two pointers are subtracted, both shall point to elements of the same array object, or one past the last element of the array object; the result is the difference of the subscripts of the two array elements.

You'll most likely get 250 if your int datatype is 4 bytes but there's no guarantee. Undefined behaviour (unlike implementation-defined behaviour) means just that, undefined. Anything can happen, up to an including the total destruction of a large proportion of space-time.

A refresher course:

  • Defined behaviour is what is mandated by the standard. Implementations must do this to be conformant.
  • Implementation-defined behaviour is left up to the implementation but it must document that behaviour clearly. Use this if you don't care too much about portability.
  • Undefined behaviour means anything can happen. Don't ever do that!
like image 106
paxdiablo Avatar answered Nov 19 '22 13:11

paxdiablo


q - p is 250.

2000 - 1000 = 1000
1000 / sizeof(int) = 250

pointer arithmetic, assuming sizeof(int) is 4.


Edit: OK, to clarify. In C when two pointers are of the same type then the difference between them is defined the number of things of the pointed-to type between them. For example,
struct foo { int ar[1000]; } big[10];
char small[10];

struct foo *fs, *fe;
char *ss, *se;

fs = &big[0]; fe = &big[9];
ss = &small[0]; se = &small[9];

fe - fs == se - ss;

That is, the difference between the two pointers in this case is the number of array elements between them. In this case it is 0, 1, ... 8 or 9 elements.

like image 8
Richard Pennington Avatar answered Nov 19 '22 13:11

Richard Pennington


q-p supposed to return how many steps with increment you should do to go from p to q. Which is 1000 / sizeof(int) and equals 250. Remember q++ will actually go to the next element of type int, not in the middle of it, so it should add 4 to the actual value of the pointer. Hence the result.

like image 2
vava Avatar answered Nov 19 '22 14:11

vava