[英]Why does this conditional cause a seg fault?
這是什么原因呢? 我認為如果指針為null,則不會評估其余條件。
// doesn't work:
char *ptr = somefunction();
if (ptr && ptr[0] == '1' || ptr[0] == 't')
// ...
// does work:
char *ptr = somefunction();
if (ptr)
if (ptr[0] == '1' || ptr[0] == 't')
// ...
ptr && ptr[0] == '1' || ptr[0] == 't'
手段:
ptr && ptr[0] == '1'
(錯誤,因為ptr
為空並且ptr[0] == '1'
沒有得到評估) ptr[0] == 't'
(景氣) 采用:
ptr && (ptr[0] == '1' || ptr[0] == 't')
代替。
您的評估順序不正確。 這將起作用:
if (ptr && (ptr[0] == '1' || ptr[0] == 't'))
基本上,只要您同時擁有&&
和||
在您的代碼中,您需要在其中加一個括號以確保它能夠達到您的期望。
您有Null ptr &&取消引用了Null ptr,這會導致段錯誤。
C使您可以選擇讓語句像if(ptr == NULL)做某事; 如果在檢測到空指針時始終將條件評估為false,則這樣的語句將不起作用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.