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...
#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;
}