0

in my little example I have created an array of the size 5 and added 3 car pointers to it. So there are 2 slots unfilled.

Question: How is it possible to find out how many pointers to cars are valid ( 3 would be correct ) without using the std lib? In the example below I tried using a loop and looking for nullptr but the check does not work.

Background: In another program I'm receiving such arrays with a fixed size and pointer to objects and would like to find out how many slots are used.

#include <iostream>

class vehicle
{
public:
  int wheels;
};

class car 
  : public vehicle
{
public:
  int power;
  int cylinders;
};

int main()
{
  int numberOfCars = 5;

  car* arrayOfCars[5];

  car benz;
  car* pBenz =&benz;
  benz.cylinders = 8;
  benz.power = 350;

  car bmw;
  car* pBmw = &bmw;
  bmw.cylinders = 6;
  bmw.power = 240;

  car vw;
  car* pVw = &vw;
  vw.cylinders = 4;
  vw.power = 120;

  arrayOfCars[0] = pBenz;
  arrayOfCars[1] = pBmw;
  arrayOfCars[2] = pVw;

  for(int idx = 0u; idx < 5; idx++)
  {
    if( (&arrayOfCars[idx]->cylinders) == nullptr)
    {
      // do something
    }
  }

  return 0;
}
HKC72
  • 502
  • 1
  • 8
  • 22
  • Do the unused elements have a special value, i.e. null? – Ulrich Eckhardt Apr 26 '22 at 14:44
  • 3
    `car* arrayOfCars[5];` is an array of 5 uninitialized pointers. Until you give each element a value, it has an indeterminate value which you are not allowed to read. You cannot assume they are initialized to `nullptr`. Use `car* arrayOfCars[5] = {};` to initialize all elements to `nullptr`. – François Andrieux Apr 26 '22 at 14:51
  • Assuming you initialize the array to hold nullptr values, then you'll also need to change `if( (&arrayOfCars[idx]->cylinders) == nullptr)` to `if(!arrayOfCars[idx])`. – Eljay Apr 26 '22 at 14:55
  • Hello all. The unused elements do not have a special value like nullpointers. Is there another way to find out how many elements are "in use" ? – HKC72 May 02 '22 at 08:08

0 Answers0