lundi 2 mars 2015

Using a pointer to traverse a dynamic allocation of classes



In the following code:



#include <iostream>

using namespace std;
class A
{
public:
int a, b, c;
A()
{
a=b=c=0;
}
};
int main()
{
A* a=new A();
A* b=a;

for(int i = 0; i < 10; i++)
{
a = new A();
cout<<a->a<<endl;
cout<<a->b<<endl;
cout<<a->c<<endl;
}
for(int i = 0; i < 10; i++)
{
cout<< b->a <<endl;
cout<< b->b <<endl;
cout<< b->c <<endl;
b++;
}

}


I am making a quasi array using pointer a. However, when I try to read this array using b, I get garbage values. The problem is that b++ isn't incrementing b by a value equal to the size of an object of class A. How can I read my "array" of classes using b?




Aucun commentaire:

Enregistrer un commentaire