I have some sort of funny question about addresses in C++. I have such code:
#include <iostream> #include <cstdlib> using namespace std; int main() { int N = 50 + rand() % 151; int arr[N]; int arr2[N]; int *ptr1; ptr1 = &arr[0]; for(int i = 0; i < N; i++){ cout << "Address1: "<< &arr[i]<< "t" << "Address2: " << &arr2[i] << endl; } }
This code works, but allocation of addresses fears me. Does such output legal? I think that it is kind of weird, that second array, locates earlier in memory than 1st array. If someone knows what’s the problem, please explain me what is wrong, because according to definition order, first must be addresses of 1st array, than addresses of second. That was compiled with g++ in Ubuntu.
Address1: 0xbf9ab1b8 Address2: 0xbf9ab028 Address1: 0xbf9ab1bc Address2: 0xbf9ab02c Address1: 0xbf9ab1c0 Address2: 0xbf9ab030 Address1: 0xbf9ab1c4 Address2: 0xbf9ab034 Address1: 0xbf9ab1c8 Address2: 0xbf9ab038 Address1: 0xbf9ab1cc Address2: 0xbf9ab03c Address1: 0xbf9ab1d0 Address2: 0xbf9ab040 Address1: 0xbf9ab1d4 Address2: 0xbf9ab044 Address1: 0xbf9ab1d8 Address2: 0xbf9ab048 Address1: 0xbf9ab1dc Address2: 0xbf9ab04c Address1: 0xbf9ab1e0 Address2: 0xbf9ab050 Address1: 0xbf9ab1e4 Address2: 0xbf9ab054 ...
Advertisement
Answer
I think that it is kind of wierd, that second array, locates earlier in memory than 1st array.
It’s not. It’s perfectly normal.
according to defenition order, first must be adresses of 1st array, than adresses of second.
I don’t know where you heard that the addresses of objects in block scope increment according to definition order. Generally, due to the nature of how stacks work, the opposite is actually true.
It really shouldn’t matter to you either way; your computer can place the objects wherever it wants.
Pick up a book on computer architecture for more information.