timeil0611
timeil0611

Reputation: 39

C++ The relationship between the address and value of a array?

int arr[3] = { 1,2,3 };
    cout <<"the address of the first element: "<< (int)arr << endl;
    cout <<"(the address of the first element)+1: " <<(int)arr + 1 << endl;
    cout << "(the value of the address of the first element)+1: " << *(arr + 1) << endl;
    cout <<"the value of the address of the second element: " <<arr[1] << endl;
    cout <<"the address of the second element: "<< (int)&arr[1] << endl;

Why does "(the address of the first element)+1" belong to the space of the first element, but it is printed out as the value of the second space (int 2)?

Upvotes: 0

Views: 57

Answers (2)

Afshin
Afshin

Reputation: 9173

At first I should say that casting address to int is an invalid operation. Results for 64 bit OS is always incorrect. You may use uintptr_t if your compiler supports.

Second thing you should know that (int)arr + 1 means cast arr to int then add one. This is an arithmetic operation on int that adds one. But arr + 1 means add 1 to pointer. This operation is pointer arithmetic which adds sizeof(int) to pointer address because pointer is int*(normally 4).

Upvotes: 2

smorgan
smorgan

Reputation: 21629

Adding 1 to an int and adding 1 to an int* are not the same operations. Adding to a pointer advances the pointer in multiples of the size of the type.

Try printing (int)(arr + 1), and you'll see that it's not the same as (int)arr + 1.

Upvotes: 2

Related Questions