I am writing a simple code to print out the elements of an array along with their respective address. I thought that the address of elements of a given array is adjacent to each other, i.e. they form a block in memory. But as the output of this code suggests, the address of adjacent elements are 4 memory units (or cells, whatever it is called) apart.
#include <iostream>
usingnamespace std;
void myfunc(int array1[], int array2[], int arrlength) {
int *p1, *p2;
p1 = array1; // p1 is a pointer that points to array2[0].
p2 = array2;
for (int i=0; i<arrlength; ++i) {
*p1 = *p1*2; // Modify the value pointed to by p1.
*(p2+i) = array2[i]+10; // Alternative way to the one above for modifying the value of an array.
++p1; // Increments p1 by 1 unit, in other words move to the next address of the elements of array2.
}
}
int main() {
int g[] = {3, 2, 6, 8};
int h[] = {1, 2, 3, 4};
myfunc(g,h,4);
for (int i=0; i<4; ++i) {
cout << g[i] << '(' << g+i << ')' << " "; // g+i is equal to the address of g[i].
}
cout << endl;
for (int i=0; i<4; ++i) {
cout << h[i] << '(' << &(h[i]) << ')' << " "; // &(h[i]) is also equal to the address of h[i].
}
cout << endl;
}
Each int value is four bytes in size (on your system - the C++ standard doesn't enforce a specific size for an int, but four bytes is common), so the address of each of those int values is four bytes from the previous int value's address.
They are all right next to each other. Each int takes four bytes.