Have I correctly allocated and de-allocated memory for 2 arrays?

I had to complete the following task

"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?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>

using namespace 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 = new double [elements];
    p_vector2 = new double [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;
}
Last edited on
Do you mean to dynamically allocate to two std::vectors or two arrays? They are not the same.

In any case, what you have written is correct. In the for loop, you can also initialize the arrays using the subscript bracket syntax like
 
p_vector1[i] = 1.0;

Last edited on
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.



^^ ninja'd :)
Topic archived. No new replies allowed.