If语句中的多指针测试

mat*_*kas 2 c testing null pointers

考虑指向结构的指针

struct a_struct  
{   
    int A; 
};  
Run Code Online (Sandbox Code Playgroud)

可以这样做:

struct a_struct *ptr;  

//...

if( ptr != NULL && ptr->A == 1)  
{  
    //work with ptr struct  
}     
Run Code Online (Sandbox Code Playgroud)

或者你应该在测试其字段之前测试指针是否有效.

if(ptr != NULL)
{
    if(ptr->A == 1)
    {
        //work with ptr struct
    }
}
Run Code Online (Sandbox Code Playgroud)

Ste*_*non 9

是的,没关系.

所述&&在C运算符短路,所以ptr->A == 1将仅在评价ptr是非空.


Hei*_*nzi 5

&&仅当第一个测试成功时才评估第二个测试,因此您的代码(一个 if语句)完全正常.