Hi i just want to check if ive deleted this array properly, but at the line where it prints arr[2] gives the right value at that location even though I have called delete when i run this. whats going on exactly?!
#include <iostream>
usingnamespace std;
int main(){
int num;
cout << "Please enter the number of values wished to be summed." << endl;
cin >> num;
int *arr = newint[num];
int temp = 0;
for(int i =0;i<num;i++){
cout << "Enter a value:"<<endl;
cin >> temp;
arr[i]=temp;
}
int total = 0;
for(int x =0;x<num;x++){
total+=arr[x];
}
delete [] arr;
cout << arr[2]<<endl;
cout << "The sum of the values is " << total << endl;
return 0;
}
That's what we call undefined behavior, meaning it may give the value that was at the location before you deleted it, it may cause your computer to blow up or maybe pink elephants will surround your house and demand all your peanuts, but usually code like this causes random segmentation faults.
No it's not correct. You should delete the array after you are finished using it. The program just happens to "work" but there is no real guarantees about what will happen.
You should learn that accessing an object or array after it has been deleted is not allowed, and avoid doing it. In many situations you can avoid the use of new/delete by using a container class. In this case you could have used std::vector<int>.
Your code with std::vector: (notice how similar it is and we don't have to care about delete because the vector will be deallocated automatically when it goes out of scope)
#include <iostream>
#include <vector>
usingnamespace std;
int main(){
int num;
cout << "Please enter the number of values wished to be summed." << endl;
cin >> num;
vector<int> arr(num);
int temp = 0;
for(int i =0;i<num;i++){
cout << "Enter a value:"<<endl;
cin >> temp;
arr[i]=temp;
}
int total = 0;
for(int x =0;x<num;x++){
total+=arr[x];
}
cout << arr[2]<<endl;
cout << "The sum of the values is " << total << endl;
return 0;
}
My apologies for replying back so late, just realized i actually hadn't even though i had read this. Thanks for the help, defs aided my understanding on the matter. :)