I read that if you take (arr+n) any number n it will just add sizeof(n) to the address
This is wrong. When n
is an int
(or an integer literal of type int
) then sizeof(n)
is the same as sizeof(int)
and that is a compile time constant. What actually happens is that first arr
decays to a pointer to the first element of the array. Then sizeof(int) * n
is added to the pointers value (because elements type is int
):
1 2 3
^ ^
| |
arr arr+2
This is because each element in the array occupies sizeof(int)
bytes and to get to memory address of the next element you have to add sizeof(int)
.
[...] and read some more stuff and found that arr[i] = *(arr+i)
This is correct. For c-ararys arr[i]
is just shorthand way of writing *(arr+i)
.
When you write some_pointer + x
then how much the pointer value is incremented depends on the type of the pointer. Consider this example:
#include <iostream>
int main(void) {
int * x = 0;
double * y = 0;
std::cout << x + 2 << "\n";
std::cout << y + 2 << "\n";
}
Possible output is
0x8
0x10
because x
is incremented by 2* sizeof(int)
while y
is incremented by 2 * sizeof(double)
. Thats also the reason why you get different results here:
#include <iostream>
int main(void) {
int x[] = {1,2,3};
std::cout << &x + 1 <<"\n";
std::cout << &x[0] + 1;
}
However, note that you get different output with int* x = new int[3]{1,2,3};
because then x
is just a int*
that points to an array, it is not an array. This distinction between arrays and pointers to arrays causes much confusion. It is important to understand that arrays are not pointers, but they often do decay to pointers to their first element.