"Write code that allocates memory dynamically to two vectors of double precision floating point numbers of length 3, assigns values to each of the entries, and then de-allocates the memory before the code terminates"
I think I correctly allocated new memory to vector 1 and 2, filled it and displayed the output so I could check. But what about deletion?
#include <iostream>
usingnamespace std;
int main()
{
//Declare pointers to 2 double variables called vector1 and vector2
int elements = 3;
double dot_product = 0;
double* p_vector1;
double* p_vector2;
//Allocate memory addresses to pointers
p_vector1 = newdouble [elements];
p_vector2 = newdouble [elements];
//Assign values to vector1 and 2's pointers as a for loop
for (int i = 0; i < elements; i++)
{
*(p_vector1 + i) = 1;
*(p_vector2 + i) = 1;
}
//Display the elements of the first vector
cout << "{";
for (int i = 0; i < elements; i++)
{
cout << p_vector1[i] << ", ";
}
cout << "}" << endl;
//Display the elements of the 2nd vector
cout << "{";
for (int i = 0; i < elements; i++)
{
cout << p_vector2[i] << ", ";
}
cout << "}" << endl;
//Delete the arrays
delete[] p_vector1;
delete[] p_vector2;
return 0;
}
it looks great. Your news and deletes are correct. little stuff that isnt wrong:
*(p_vector1 + i) = 1;
*(p_vector2 + i) = 1;
consider
p_vector1[i] = 1; //same result, a little easier on the eyes, and you used this notation later, use the same style in the same code for consistency.