How does pointer increment work?

We have an array: int p[100].
Why is it p[i]equivalent *(p+i), not *(p+i*sizeof(int))?

+1
source share
5 answers

Why is p [i] equivalent to * (p + i) and not * (p + i * sizeof (int))?

Because some processor architectures cannot dereference a pointer that does not point to an address that is aligned in size with its type. This means that a pointer to a 4 byte integer should always point to an address that is a multiple of 4.

When a program tries to dereference an invalid pointer, it can cause a "Bus" error. You can learn more about this here on Wikipedia .

, , p + 1 . , p++ , char. , * sizeof(*p), .

, , , .

+3

p [i] *(p+i), *(p+i*sizeof(int))?

*(p+i) *((int *) ((char *) p + i * sizeof (int))). i , i .

+7

, i to p p, i p.

+1
source

Array elements are stored contiguously.

*(p+i)

Here p has the base address of the array p and I am from 0 to 99.

So you can iterate over p elements by increasing i.

0
source

Why is p [i] equivalent *(p+i)and not *(p+i*sizeof(int))?

This is due to how pointer arithmetic works: adding an integer nto the pointer gives a pointer to the nith element (not byte) from first to (based on 0).

0
source

Source: https://habr.com/ru/post/1618023/


All Articles