12
int main()
{
    int arraySize;
    int arrayMain[arraySize-1];
    cout << "\n\nEnter Total Number of Elements in Array.\n\n";
    cin >> arraySize;
    arrayMain[arraySize-1]={0};
    cout <<"\n\n" <<arrayMain;
    return 0;
}

my compiler freezes when I compile the above code. I am confused on how to set a dynamic array to 0?

3 Answers 3

20

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.

Sign up to request clarification or add additional context in comments.

2 Comments

i have to use in int array
How about std=c++11?
10

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

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

3 Comments

I'm not sure if that's a valid answer. Because, it just initializes the very first element of array to the value in brackets. For example int *p = new int[n]{1}; will set just the p[0] to 1.
This just initializes the first element of array to the number specified
Yes @shiwang You are right when you want to initialize other then 0. But for 0 this will works :)
5

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';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.