Chris
Chris

Reputation: 1

Cannot access memory at adress 0x

I have this project where I must create a society of objects (creatures) which is a separate object. I'm trying to do this by initializing an array of pointers to the object creature inside creature_society's constructor (good and bad creatures are classes that inherit the class creature which is abstract)

creature_society::creature_society(int n, int L, int good_thrsh, int bad_thrsh)
{
  int a;
  creature **cArray = new creature * [n];
  gthrsh = good_thrsh;
  bthrsh = bad_thrsh;

  for(i = 0; i < n; i++)
  {
    a = rand() % 2 ;
    if(a == 1)
      cArray[i] = new good_creature(L, i);
    else
      cArray[i] = new bad_creature(L, i);

    cout<< "\nhp is "<< cArray[i]->gethp() << "\n" << endl;
  }
}

Everything works fine, creature society and the creatures are created but when I try to change a value of cArray[i] via a creature class function e.g.

void creature::bless()
{
  if(!is_a_zombie()) 
    hp++;
}

I get a segmentation fault and I get the message

cannot access memory at address 0x..

So my question is, why am I getting it? Is there something wrong with the cArray initialisation?

Upvotes: 0

Views: 919

Answers (1)

Georg
Georg

Reputation: 324

cArray is set during creature_society::creature_society

creature **cArray=new creature * [n];

outside of this method, you cannot access this variable. If you have another (global?) variable cArray, this will not be changed and probably stay at a value of 0, therefore pointing to address 0x.

Upvotes: 1

Related Questions