-2

I have a code where I am pointing to a nested sub structure element. Like:

struct bucket *hp = array->value.ht->pListHead;

I am getting the pListHead value. But Im wondering if there is chance of one of the pointer being NULL. One way of checking the validity of this redirection is to check each pointer like

if(array)
  if(array->value)
    if(array->value.ht)
      if(array->value.ht->pListHead)
        struct bucket *hp = array->value.ht->pListHead;

Is there any other solution of doing this validation ?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
RishiN
  • 39
  • 5
  • 4
    Yes, redesign everything so none of the validation necessary, by implementing this functionality via classes with a design-based contract that makes it logically impossible for null pointers to exist. And, in the worst case, use smart pointers that check nullptr for you and throw an exception. – Sam Varshavchik Jul 22 '19 at 11:02
  • 1
    Please choose a single language. C and C++ have almost nothing in common. – Quentin Jul 22 '19 at 11:03
  • @Quentin Well, they have C in common. I agree, though. C++ would maybe allow to create some template which does that while it would not be viable answer for C. – Piotr Siupa Jul 22 '19 at 11:07
  • 3
    @NO_NAME no, they don't. There exists a subset of C and C++ that could be described as either "crappy C" or "abysmal C++" and happens to be usable enough to write code, but should really be confined to polyglot library headers. – Quentin Jul 22 '19 at 11:10
  • 1
    Either this `value.ht` or this `if(array->value)` both at the same time is not possible. – alk Jul 22 '19 at 12:09

1 Answers1

4

You can rewrite as one if statement

if ( array && array->value && array->value.ht && array->value.ht->pListHead )
{
   // ...
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335