Trying to understand pointer and address

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
  #include <iostream>
using namespace 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;
}
An array of int values.

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.
Last edited on
I see, so the memory cell is represented by the bytes.
Topic archived. No new replies allowed.