1
我已經通過堆棧溢出幾個類似的問題,但我一直沒能找到一個可以幫助我理解這種情況下的警告。儘管如此,我還是在嘗試學習C的第一週,所以如果由於缺乏理解而錯過了堆棧溢出的其他明顯答案,我很抱歉。傳遞參數使整數指針沒有轉換
我得到以下警告和注意事項:
warning: passing argument 2 of ‘CheckIfIn’ makes pointer from integer without a cast [enabled by default]
if(CheckIfIn(letter, *Vowels)){
^
note: expected ‘char *’ but argument is of type ‘char’
int CheckIfIn(char ch, char *checkstring) {
當試圖編譯這段代碼:
#include <stdio.h>
#include <string.h>
#define CharSize 1 // in case running on other systems
int CheckIfIn(char ch, char *checkstring) {
int string_len = sizeof(*checkstring)/CharSize;
int a = 0;
for(a = 0; a < string_len && checkstring[a] != '\0'; a++){
if (ch == checkstring[a]) {
return 1;
}
}
return 0;
}
// test function
int main(int argc, char *argv[]){
char letter = 'a';
char *Vowels = "aeiou";
if(CheckIfIn(letter, *Vowels)){
printf("this is a vowel.\n");
}
return 0;
}
修復類型:'CheckIfIn(letter,* Vowels)'應該是'CheckIfIn(letter,Vowels)'。然後'sizeof(* checkstring)/ CharSize'不是你所期望的。 – Jarod42 2014-08-30 16:50:57
'#define CharSize 1 //在其他系統上運行時''''char'的大小始終爲1,即使在非8位系統上也是如此。因此,在所有系統上,int string_len = sizeof(* checkstring)/ CharSize;總是計算爲1。你需要將一個數組的長度作爲一個單獨的參數傳遞給一個函數,或者如果你的數組有一些sentinel值(比如字符串的0字節),可以使用'strlen'這樣的函數:'size_t string_len = strlen(checkstring );'。 – mafso 2014-08-30 17:12:22
另外。由於你不想修改元音指向的字符串,所以你應該將它聲明爲一個'const char *'(一個指向'const'字符串的指針),並將'CheckIfIn'的參數類型從char *到'const char *'。 – John 2014-08-30 18:18:43