How can I correctly set all elements of an array t

2020-05-09 10:09发布

问题:

I have a program where it asks the user to for a certain amount and elements and creates the array, and then after initializing all elements to zero, it now sets all elements to negative -1. I have a segmentation fault and I think it's due to my code for setting the elements to -1. What would be a better way for set all elements to negative one? And if possible, explain why.

#include <cstddef>
#include <iostream>
using namespace std;

int main(int argc, char * argv[]) {  

    cout << endl << "A dynamic array creation program" << endl;

    size_t length = 0;  
    int * intArray = nullptr;  

    cout << endl << "Input number of elements: ";  
    cin >> length;  

    cout << endl << "Allocating memory to create the dynamic array" << endl;  
    intArray = new int [length];  

    cout << endl << "Initializing all elements to 0" << endl;  
    for (size_t i=0; i<length; ++i)    
        intArray[i] = 0;  

    cout << endl << "Deallocating the dynamic array" << endl;  
    delete [] intArray;  
    intArray = nullptr; 

    cout << endl << "Setting all elements to negative values" << endl;  
    for (size_t i=0; i<length; ++i)    
        intArray[i] = -1;  
    return 0;
}

回答1:

after initializing all elements to zero, it now sets all elements to negative -1.

It does something else after setting all elements to zero. It deletes the array. The elements no longer exist at the point where you assign -1.

What would be a better way for set all elements to negative one?

Doing it before the array is deleted.

And if possible, explain why.

Because if you attempt to access objects outside of their lifetime, the behaviour of the program will be undefined.