4.3 Write code that allocates memory dynamically to two vectors of double preci-
ID: 3738082 • Letter: 4
Question
4.3 Write code that allocates memory dynamically to two vectors of double preci- sion floating point numbers of length 3, assigns values to each of the entries, and then de-allocates the memory before the code terminates. Extend this code so that it calculates the scalar (dot) product of these vectors and prints it to screen before the memory is de-allocated. Put the allocation of memory, calculation and de-allocation of memory inside a for loop that runs 1,000,000,000 times: if the memory is not de-allocated properly your code will use all available resources and your computer may struggle.Explanation / Answer
#include <iostream>
using namespace std;
int main() {
double *d1, *d2;
double product = 0;
for(long i = 0; i < 1000000000; ++i) {
d1 = new double[3];
d2 = new double[3];
product = (d1[0]*d2[0]) + (d1[1]*d2[1]) + (d1[2]*d2[2]);
delete[] d1;
delete[] d2;
}
return 0;
}
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.