Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/64.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 传递参数从整数生成指针,无需强制转换_C - Fatal编程技术网

C 传递参数从整数生成指针,无需强制转换

C 传递参数从整数生成指针,无需强制转换,c,C,我已经通读了几个关于堆栈溢出的类似问题,但还没有找到一个能帮助我理解本例中的警告的问题。不过,我正处于尝试学习C语言的第一周,因此,如果由于缺乏理解,在堆栈溢出的其他地方遗漏了一个明显的答案,我深表歉意 我得到以下警告和注意: warning: passing argument 2 of ‘CheckIfIn’ makes pointer from integer without a cast [enabled by default] if(CheckIfIn(letter, *Vowels

我已经通读了几个关于堆栈溢出的类似问题,但还没有找到一个能帮助我理解本例中的警告的问题。不过,我正处于尝试学习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;
}
#包括
#包括
#定义CharSize 1//以防在其他系统上运行
int CheckIfIn(字符ch,字符*校验字符串){
int string_len=sizeof(*checkstring)/CharSize;
int a=0;
对于(a=0;a
元音
是一个
字符*
*元音
只是一个
字符
,“a”
char
s自动升级为整数,编译器允许将其隐式转换为指针。但是,指针值不会是元音,而是几乎通用地等于字符“a”的整数编码0x61的地址


只需将
元音
传递给函数。

在您的例子中,类型转换是从
字符
整数
指针。在某些情况下,函数将void pointer作为第二个参数,以适应所有数据类型。 在这种情况下,您需要将第二个参数类型转换为
(void*)

这将是大多数编写良好的模块化函数中的函数声明:

int CheckIfIn(char ch, void *checkstring);
如果元音不是char指针,则需要将参数作为void指针传递

 if(CheckIfIn(letter, (void *)Vowels) ){
        printf("this is a vowel.\n");
    }

要修复类型:
CheckIfIn(字母,*元音)
应该是
CheckIfIn(字母,元音)
。那么
sizeof(*checkstring)/CharSize
就不是您所期望的。
#定义CharSize 1//以防在其他系统上运行
-
char
的大小始终为1,即使在非8位系统上也是如此。因此,
intstring\u len=sizeof(*checkstring)/CharSize的计算结果始终为1。您需要将数组的长度作为一个单独的参数传递给函数,或者如果数组有一些前哨值(如字符串的0字节):
size\t string\u len=strlen(checkstring)。还有。因为您不想修改元音指向的字符串,所以应该将其声明为
const char*
(指向
const
字符串的指针),并将
CheckIfIn
的参数类型从
char*
更改为
const char*
。谢谢大家的帮助-非常有用。正如你所看到的,我犯了一些基本的错误。我不介意谁否决了解释否决票。我并不是说投反对票是不合法的,但是如果你不告诉人们你认为他们做错了什么,那么投反对票就不会有什么效果——我认为这是一种糟糕的论坛行为。