2010-09-05 30 views
2

我在下面的代碼中得到了錯誤assignment makes pointer from integer without a cast,這是什麼意思?C++:strchr上的指針分配警告()

char * splitter; 
if(splitter = strchr(key, ':') != NULL && *(splitter + 1) == ' ') 
+0

相關(不重複)http://stackoverflow.com/questions/3626905/why-does-this-c-program-print-weird-characters-in-output/3626912#3626912 – codaddict 2010-09-06 02:44:18

+0

爲了便於閱讀,應該將該分配移出if語句。另外'*(splitter + 1)'相當於'splitter [1]'。 – sellibitze 2010-09-06 05:35:45

回答

1

!=操作符比=操作者更高的優先級。這意味着您的表達式splitter = strchr(key, ':') != NULL實際上被解釋爲splitter = (strchr(key, ':') != NULL)

將分配到括號以增加部分的優先級:

(splitter = strchr(key, ':')) != NULL 
2

的不等於運算符=比賦值運算符的優先級高=,所以你的原始行讀起來就像splitter = (strchr(key, ':') != NULL)而不是你意圖(splitter = strchr(key, ':)) != NULL,因此編譯器試圖將分配器分配給strchr()和NULL之間的比較結果。

1

!==有更高的優先權。您應該完全加入括號:

if (((splitter = strchr(key, ':')) != NULL) && (*(splitter + 1) == ' ')) 
3

這是因爲操作的優先級。你需要把一組額外的括號的,以確保它在正確的順序發生了:

char * splitter; 
if((splitter = strchr(key, ':')) != NULL && *(splitter + 1) == ' ') 

否則就被當作是:

splitter = (strchr(key, ':') != NULL) 

由於strchr(key, ':') != NULL將評估到任何一個1或一個0,在你的例子中,你正在給一個指針類型分配一個整數,因此是警告。但是,我只是把它寫在你的第二個例子中,因爲它更簡單並且更不容易出錯。縮短一行不會增加任何內容,除了複雜性。

+0

我會寫'splitter [1]'而不是'*(splitter + 1)'。 – 2010-09-05 19:19:01