Home > Net >  Is it possible for an address of an std::array member to be null in C ?
Is it possible for an address of an std::array member to be null in C ?

Time:01-22

Is it possible to modify a to make the if-statement fail?

std::array<int,4> a = {{1,2,3,4}};

for (int i=0;i<a.size();i  )
{
    auto ptr = &a[i];
    if (ptr != nullptr)
    {
        printf("value at %d is %d\n",i,a[i]);
    }
    else
    {
        printf("Invalid array\n");
    }
}

CodePudding user response:

The address of an element in a standard library container can't be null, as long as you are using the container's API properly. This is because, assuming you meet all preconditions of the API, the container guarantees that all of its elements are valid objects, and a valid object never has a null address. As soon as you violate the preconditions, however (for example, popping from an empty vector), the entire program has undefined behaviour, and you might end up seeing "impossible" branches of if statements getting executed.

In the snippet shown, for example, attempting to access a[4] will give the program undefined behaviour. It probably will not result in the else branch being taken, but you never know.

CodePudding user response:

The if (ptr != nullptr) block is entirely redundant. It does nothing. The test can never fail. The std::array<int, 4> is created right there as a local automatic variable, it can not fail to have a valid address for all its elements.

  •  Tags:  
  • Related