今天在遇到一个“||” 操作符引发的小问题,与君分享。
/* 链表结构体和数据类型定义*/
typedef int Elem;
/*Node Type*/
typedef struct Node{
Elem eData;
struct Node *Next;
}Node_s;
/*初始化链表,只有一个表头结点*/
int init_list(Node_s **pNode)
{
*pNode = (Node_s *)malloc(sizeof(Node));
if (NULL == *pNode){
exit(0);
}
(*pNode)->Next = NULL;
return 1;
}
情况1:
int main()
{
Node_s **pNode, *current;
init_list(pNode);
current = (*pNode)->Next;
if (NULL == current->Next || NULL == current){
printf("Hello!\n");
}
return 0;
}
结果:程序崩溃
情况2:
int main()
{
Node_s **pNode, *current;
init_list(pNode);
current = (*pNode)->Next;
if (NULL == current || NULL == current->Next){
printf("Hello!\n");
}
return 0;
}
分析:情况1中,很明显current->Next 是不存在的,是一个野指针,所以程序会崩溃。
情况2中,由于current==NULL条件成立,故“||”操作符右操作数不执行,故程序不崩溃。
经验:有时候,我们的思维是正确的,但要注意一些细节,多思考,多想。