user2086751
user2086751

Reputation:

initializing a dynamic array to 0?

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?

Upvotes: 12

Views: 49182

Answers (3)

Jaydip Pansuriya
Jaydip Pansuriya

Reputation: 214

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

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

Upvotes: 9

hmjd
hmjd

Reputation: 122011

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

Upvotes: 5

Luchian Grigore
Luchian Grigore

Reputation: 258678

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.

Upvotes: 20

Related Questions