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