Skip to content

Dynamic allocation (1)

Course: C++ Part 2 - chapter 3

One way to create dynamic arrays is using pointers. Dynamic allocation allocates memory in the heap space.

As mentioned, pointers holds the address of a variable. If we can occupy consecutive memory locations, we can use pointers to iterate on them without additional help. How?

The pointer holds the base address / first element address. The type of pointer determines the type of variable it points to, for example integer pointers are pointing to integer variables. So from that we know the memory each variable uses (Ex 4 bytes for integers). So we can just increment the base address by 4 bytes to get the address of the next element. This is called pointer arithmetic.

int *ptr;
// Let's say ptr stores 2000 which is address of a variable
// Data type of the variable is integer - 4 bytes
ptr++; // ptr becomes 2004 i.e address of the next element
ptr--; // ptr becomes 1996 i.e address of previous element
ptr = ptr + sizeof(type)
int *arr;
int n;
cin>>n;
arr = new int[n];
// Now we can do normal array operations
for(int i=0; i<n; i++) cin>>arr[i];

Let’s understand what happens when we do arr[i].

Internally it translates into this:

arr[i] = *(arr + i)

Now by pointer arithmetic, it should skip by the size of the data type. So,

arr[i] = *(arr + i * sizeof(int))

The name of the array (i.e arr) holds the base address.