Bold Aesthetic Creative Games

An Indie Game Studio Developing Bold, Aesthetic & Creative Video Games

C++ Programming Series: Dynamic Arrays (Part 2, Last)

C++ Programming Series: Dynamic Arrays (Part 2, Last)

Dynamic arrays can be used with functions in exactly the same way as I have told in this post. Just keep in mind that we have to pass the size of the array into the function.

void printIntegerArray(int* pArr, int totalElements)
{
    for(int i = 0; i < totalElements; i++)
    {
        cout << pArr[i] << endl;
    }
}

int main()
{
    int* array = new int[5] { 3, 4, 7, 8, 12 };

    printIntegerArray(array, 5);

    return 0;
}

Note how I allocated the memory and also, set the value of all the elements in the dynamic array in the highlighted line.

That initialization of dynamic array is what the real purpose of this small post is. Why? Because dah! I learned that very late. Very very late.

At least, I am able to save others from this.

array[0] = 3;
array[1] = 4;
//...till the end :p

Also, there is another purpose of this post.

Tell me my mistake in the code.

If you already knew it before reaching this part, you must be a keen observer. There is no delete[] array; at the end of the code.

Damn those memory bees. (By the way, it is a genuine mistake)

This ends my C++ Programming Series. Now, to ease your path, there will be another post in this series. Keep coming back and you will always find a bunch of useful stuff here.

Leave a Reply

Your email address will not be published. Required fields are marked *