2

Suppose you have a pointer, produced by something like

int a = 5;
int* pointer = &a;

And suppose you add 1 to the pointer, as in

pointer = pointer + 1;

Now suppose the original bitwise representation of the pointer was

00000000 00000000 00000000 00000000

Then is the new representation 00000000 00000000 00000000 00000001? Or 00000000 00000000 00000001 00000000? Or neither of those?

I am confused because I feel like adding 1 to a number should add 1 to its bitwise representation. But if you add 1 to the index of an array, the new address is 32 bits away from the old address.

Jessica
  • 2,335
  • 2
  • 23
  • 36

2 Answers2

6

When you add 1 to pointer, then compiler do the following arithmetic behind the scene

pointer = pointer + sizeof(int)*1  

So, it will depend on the size of data type. On a 32-bit machine size of int is 4-bytes, therefore 4*1 = 4 will be added to pointer.

For example, if pointer is pointing to memory addresss 0x00000000 then it will be pointing at 0x00000004 after adding 1 to it.

enter image description here

Community
  • 1
  • 1
haccks
  • 104,019
  • 25
  • 176
  • 264
3

It depends on the type of pointer.

The pointer actually are all the same, as far as the actual data is concerned. An int* keeps the same kind of data as a char* (integer values representing memory locations). The reason why we care about the kind of data a pointer points to is, besides knowing how to decode it (i.e. dereference it), to know how to point to the next element of the same type. So, let p be a pointer to an object (object not as in oop, but as any variable that has some storage associated) of type T. Then, intptr_t(p + 1) = intptr_t(p) + sizeof(T).

This is particularly useful in working with arrays and, if you think a little bit, it makes sense. Consider the declaration int *p = 0x100 and assume that at address 100 is a valid integer value. What sense would it make to access the integer value from 0x101 (this is actually illegal, since ints must start on addresses divisible by 4 - considering sizeof(int) = 4)?

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
Paul92
  • 8,827
  • 1
  • 23
  • 37