Pointers, Dynamic Arrays and Structures

Hi guys! I've started learning C++ like a few months back, but I'm stumped with a concept. I've searched the web but I couldn't get the answer I needed.

I understand that:

(*a).b is equivalent to a->b.

If I create a pointer of an array of structures, why I can't:

(*a[x]).b ~ a[x] -> b?

Is it because array and pointer are "correlated"?

Also, what is the difference between "haha * a [] = new haha;" and
"haha * a = new haha [];"?

Not sure if I got the concepts right but yea, self-learning is a little tough...
Last edited on
closed account (D80DSL3A)
The use of [] dereferences the pointer. However, all notations you've listed can be used in the right situations.
Examples in code:
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
45
46
47
48
49
50
#include<iostream>
//#include<vector>

//using namespace std;

class A// for demo purposes
{
public:
    int x;
    A():x(75) { std::cout << "no-arg ctor\n"; }
    A(int _x):x(_x) { std::cout << "1-arg ctor\n"; }
    A( const A& a ):x(a.x) { std::cout << "copy ctor\n"; }
    A& operator=( const A& a ) { x = a.x; std::cout << "oper =\n"; return *this; }
    ~A() { std::cout << "dtor called\n"; }
};

int main()
{
    A a[3] = { A(1), A(2), A(3) };

    // the [] dereferences the pointer, so no * is needed.
    std::cout << "1st element = " << a[0].x << '\n';
    // use pointer notation to avoid the automatic dereference performed by[]
    std::cout << "2nd element = " << (a+1)->x << '\n';

    // 2nd question
    // allocating new A's to an array of pointers
    A* pA_array[3] = { new A(3), new A(7), new A(9) };
    //     usage. Note use of both [] and -> since we have an array of pointers, not an array of A's
    for( int i=0; i<3; ++i ) std::cout << pA_array[i]->x << ' ';
    std::cout << '\n';
    // the (*a[b]).x notation may also be used
    for( int i=0; i<3; ++i ) std::cout << (*pA_array[i]).x << ' ';
    std::cout << '\n';
    // cleanup - release memory
    for( int i=0; i<3; ++i ) delete pA_array[i];// delete the A allocated to each pointer

    // allocating an array of A's to a single pointer
    A* pA = new A[3];// all will be default initialized so that x=75. See no-arg constructor.
    // using pointer notation
    for( int i=0; i<3; ++i ) std::cout << (pA+i)->x << ' ';
    std::cout << '\n';
    // cleanup - release memory
    delete [] pA;// delete the array of A's allocated to the single pointer

    std::cout << "\nNow the dtors for the stack allocated A's \n";


    return 0;
}


EDIT: Added cleanup for dynamic memory usage.
Last edited on
Thanks for the information! It clears up my doubts!
Topic archived. No new replies allowed.