Reputation: 904
We have an array: int p[100]
.
Why p[i]
is equivalent to *(p+i)
and not *(p+i*sizeof(int))
?
Upvotes: 1
Views: 152
Reputation: 4036
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.
Upvotes: 3
Reputation: 91139
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 n
th element (not byte) from the first on (0-based).
Upvotes: 0
Reputation: 106102
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
.
Upvotes: 1
Reputation: 17920
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.
Upvotes: 0
Reputation: 145899
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.
Upvotes: 7