Dynamic array initialization 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 hangs while compiling the above code. I am confused about how to set a dynamic array to 0?

+3


source to share


2 answers


You are using std::vector

:

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

      

Your code is invalid because 1) is arraySize

not initialized and 2) you cannot have variable length arrays in C ++. So either use a vector or allocate memory dynamically (this is what it std::vector

does internally):



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

      

Notice at ()

the end - he used a value to initialize the elements, so the array will have its elements set to 0.

+8


source


If you must use a dynamic array, you can use value initialization (although std::vector<int>

would be the recommended solution):

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

      

Check the result of the input operation to make sure the variable has been assigned the 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 usage cout

:

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

      

will print the address of the array arrayMain

, not every single element. To print each user, you need to index each element in turn:

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

      

+3


source







All Articles