Assigning an address of an array to a variable and delete

3940 views c++
8

My assignment wants me to do this: "Allocate an array of seven ints; initialize it to 1,2,4,8, etc...; and assign its address to a variable p2"

This was my code:

int* p2 = new int[7] {1,2,4,8,16,32,64};
    cout << "Drill 3 & 4 (allocating 7 element array): " << endl;
    for (int i = 0; i < 7; ++i) {
        cout << p2[i];
    }

but I am concerned that I am misunderstanding the instructions. Because of that, I tried this code I found online:

int* sev = new int[7];
for (int i = 0; i<7; ++i)
    sev[i] = i+1;
int* p2 = sev;
cout << "p2= " << p2 << ", *p2=" << *p2 << endl;
cout << "sev= " << sev << ", *sev=" << *sev << endl;

But it outputs the address and then 1. And when I add a for loop to do it seven times for all of the elements, it's just 1111111.

Is my code above assigning the address to the pointer or doing something different?

I later have to make it equal to p1, which is a pointer (*int p1 = &x, x = 7 <--not code, for reference). And I need to deallocate p1 and p2 (and p3, but that's not relevant). It lets me deallocate p2, but not p1. So, I am thinking maybe I am not understanding the question or am not approaching it correctly.

answered question

1 Answer

13

Both the variable sev and the variable p2 are pointing to the first element of the data you have allocated. That's really all you have.

So when you dereference the pointers (with e.g. *sev) you dereference the pointer to that element only, and get that value only.

A more "graphical" way of looking at your "array" might be like this:

+--------+--------+--------+--------+--------+--------+--------+
| sev[0] | sev[1] | sev[2] | sev[3] | sev[4] | sev[5] | sev[6] |
+--------+--------+--------+--------+--------+--------+--------+
^
|
sev / p2

The arrow points to the first element only.

posted this

Have an answer?

JD

Please login first before posting an answer.