传递'fgets'的参数1使得指针来自整数而没有强制转换

时间:2016-04-03 16:05:47

标签: c fgets

我运行这段代码,我得到以下错误,我做了一些研究,但我没有真正得到答案,我希望如果有人能给我一点帮助。我是编程新手,如果我错过了太明显的东西,请饶我。

  

[警告]传递'fgets'的参数1会使整数的指针没有强制转换

int main(int argc, char *argv[]) {
 char *t,*s;
 char first, second;
 int x;

 printf("Give the first string: ");
 fgets(first,sizeof(char),stdin);
 printf("Give the second string: ");
 fgets(second,sizeof(char),stdin);
}

当我添加“&”时在我编译的“第一”和“第二”变量中,但是当我运行它时,我没有得到我从键盘上给出的字符串。

如何编译?

3 个答案:

答案 0 :(得分:1)

fgets期望char*指向缓冲区,因为它是第一个参数

答案 1 :(得分:0)

int main(int argc, char *argv[]) {
    char first[80], second[80];

    printf("Give the first string: ");
    fgets(first, sizeof(char), stdin);
    printf("Give the second string: ");
    fgets(second, sizeof(char), stdin);
}

fgets表示"从文件"中获取字符串,并且您需要一个char数组来保存字符串。

答案 2 :(得分:0)

你应该先将第一个和第二个转换为指针并分配空间以填充它们

int main(int argc, char *argv[]) {

int flen = 256;
int slen = 256;
 char* first = malloc(flen); //allocate enough space to handle verbose typists :)
 char* second = malloc(slen);
 int x;

 printf("%s\n","Give the first string: ");
 fgets(first,flen,stdin);

 printf("%s\n","Give the second string: ");
 fgets(second,slen,stdin);

//do something with first and second.

//free memory you allocated
free(first);
free(second);
};