How can I correctly set all elements of an array to a negative value?

对着背影说爱祢 提交于 2020-04-07 08:50:30

问题


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.



来源:https://stackoverflow.com/questions/60873525/how-can-i-correctly-set-all-elements-of-an-array-to-a-negative-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!