如何正确将数组的所有元素设置为负值? [英] How can I correctly set all elements of an array to a negative value?

查看:808
本文介绍了如何正确将数组的所有元素设置为负值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序,其中要求用户输入一定数量和元素并创建数组,然后将所有元素初始化为零后,现在将所有元素设置为负-1.我有一个分割错误,我认为这是由于我的代码将元素设置为-1所致.将所有元素设置为负数的更好方法是什么?并尽可能解释原因.

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.

将所有元素设置为零后,它还会执行其他操作.删除数组.元素在分配-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.

这篇关于如何正确将数组的所有元素设置为负值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆