if i write something like this it works:

Person array_persons[10];

     int age=0;
     for(int i=0; i<10; i++)
     {
             
         cout<<"give age : "<<i<<endl;
         cin>>age;
         array_persons[i].setAge(age);
     }

but when i try to do it with pointers:

Person *array_persons[10];

     int age=0;
     for(int i=0; i<10; i++)
     {
             
         cout<<"- give age : "<<i<<endl;
         cin>>age;
         array_persons[i]->setAge(age);
     }

it doesn't work[although it does compile]??!!

any ideas?

thanks
N.A.

It doesn't work because you have not allocated any memory for the objects. array_persons is just an array of 10 pointers that point to some random memory locations. You need to allocate memory using new operator.

array_persons[i] = new Person;

and don't forget to free up the memory before the program terminates using delete

thanks, you are right

to delete memory i would write:

for(int i=0; i<10; i++)
     {
         delete array_persons[i];
     }

i think i don't need to write anything else....

thanx again :)

Deleting dynamically allocated array is done in C++ using the special delete syntax : delete[] array_persons ; where you had allocated the array with something like: int* array_persons = new int[10] ; An eg.

int main()
{
    int* a = new int[10] ;
    for( int i = 0; i < 10; ++i )
    {
        a[i] = i ;
    }
    delete[] a ;
    return 0 ;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.