I found the address of the next array of the first array in 2 different ways. In two dimensional array both method gives the same address of next aaray But in one dimensional array both method gives different adresses What is the reason for that? How can I get the right answer?
int main()
{
cout<<"In 2D Array------>"<<endl<<endl;
int a[4][3]={{1,2,3},
{4,5,6},
{7,8,9},
{10,11,12}};
int b[4][3]={{1,2,3},
{4,5,6},
{7,8,9},
{10,11,12}};
cout<<"Address of first Array = "<<&a<<endl<<endl;
cout<<"Address of Next Array = "<<&a 1<<endl;
cout<<"Address of Next Array = "<<&b<<endl<<endl;
cout<<endl<<endl<<endl<<endl<<endl;
cout<<"In 1D Array----->"<<endl<<endl;
int A[]={1,2,3,4,5};
int B[]={1,2,3,4,5};
cout<<"Address of first Array = "<<&A<<endl<<endl;
cout<<"Address of Next array = "<<&A 1<<endl;
cout<<"Address of Next array = "<<&B<<endl<<endl;
return 0;
}
CodePudding user response:
For starters the order in which the compiler will place variables with automatic storage duration is unspecified. So it is not necessary that for example the array b will be placed after the array a or vice versa.
Secondly the compiler can align arrays for example on the bound of paragraph that is equal to 16 bytes.
So relative to your program it seems that the compiler placed the array b after the array a without a gap.
But the array B placed after the array A was aligned on the bound of 16 bytes or on some other value. So there is a gap between these two array definitions.
You can experiment for example by reducing the number of elements in the arrays A and B to 4
int A[]={1,2,3,4};
int B[]={1,2,3,4};
CodePudding user response:
This cannot be done between one array and another because the array is defined in random places on memory.
But you can find the address of all the elements of the array by putting the tag then the name of the array and then typing [index] the location of the element you want to know its address and the address varies according to the data type of the array Example if the type of the array is int , the increment will be in hexadecimal many by 4 bytes between one element and another Example:
cout<<"Address of first Array = "<<&A[0]<<endl<<endl;
cout<<"Address of Next array = "<<&A[1]<<endl;
cout<<"Address of Next array = "<<&A[2]<<endl<<endl;