initializing a dynamic array to 0?

if you want to initialize whole array to zero do this ,

int *p = new int[n]{0};

If you must use a dynamic array you can use value initialization (though std::vector<int> would be the recommended solution):

int* arrayMain = new int[arraySize - 1]();

Check the result of input operation to ensure the variable has been assigned a correct value:

if (cin >> arraySize && arraySize > 1) // > 1 to allocate an array with at least
{                                      // one element (unsure why the '-1').
    int* arrayMain = new int[arraySize - 1]();

    // Delete 'arrayMain' when no longer required.
    delete[] arrayMain;
}

Note the use of cout:

cout <<"\n\n" <<arrayMain;

will print the address of the arrayMain array, not each individual element. To print each individual you need index each element in turn:

for (int i = 0; i < arraySize - 1; i++) std::cout << arrayMain[i] << '\n';

You use a std::vector:

std::vector<int> vec(arraySize-1);

Your code is invalid because 1) arraySize isn't initialized and 2) you can't have variable length arrays in C++. So either use a vector or allocate the memory dynamically (which is what std::vector does internally):

int* arrayMain = new int[arraySize-1] ();

Note the () at the end - it's used to value-initialize the elements, so the array will have its elements set to 0.

Tags:

C++

Arrays