1

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

5 Answers 5

7

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

Because *(p+i) is also the same as *((int *) ((char *) p + i * sizeof (int))). When you add an integer i to a pointer, the pointer is moved i times the size of the pointed object.

Sign up to request clarification or add additional context in comments.

Comments

3

Why p[i] is 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 by the size of its type. That basicly means that a pointer to a 4 byte integer should always point to an adress that is the multiple of 4.

When a program tries to dereference a misaligned pointer it might cause a "Bus error". You can read more about it here on Wikipedia.

What you are asking for is that p + 1 should increment the pointer by one byte instead of one element. If the language was designed that way writing p++ would no longer be valid for pointers of other types than char. It would also cause big problems with pointer alignment when a programmer forgets to write * sizeof(*p) to make the addition.

It might be confusing but there are very valid reasons for why the language was designed this way.

Comments

1

This is because before adding i to p compiler calculates internally the size of data type p points to and then add it i times to p.

Comments

0

Array elements are stored contiguously.

*(p+i)

Here p has the base address of array p and i ranges from 0 to 99.

So you can iterate over the elements of p by incrementing i.

Comments

0

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

This is because of the way pointer arithmetics work: adding an integer n to a pointer yields a pointer to the nth element (not byte) from the first on (0-based).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.