C取消引用指针警告,甚至认为它们都是字符

时间:2018-03-19 16:10:57

标签: c pointers stdin fgets

我有一些代码可以通过stdinfgets获得输入。

我需要检测用户何时没有输入,因为这会破坏我的其他代码。

这是我的代码:

#include <stdio.h>
int main(void){
  char input[100];
  char first;
  printf("Input something:\n>\n");
  first = (char)(&fgets(input, 100, stdin)[0]);
  if(first == "\n"){
    // handle empty input here...
  }
}

问题在于它给了我一个警告:

main.c:6:10: warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]
first = (char)(&fgets(name1point, 100, stdin)[0]);
        ^

除了firstfgets的第一个字符都是char类型。

如果我这样做

if(fgets(input, 100, stdin)[0] == "\n"){
然后它给了我一个警告:

main.c:7:12: warning: comparison between pointer and integer
  if(first == "\n"){
           ^~

那么我需要取消引用它。

任何人都可以帮助我吗?我是初学者。

1 个答案:

答案 0 :(得分:1)

有几件事:

  • fgets()返回一个char *,所以&amp; fgets()是一个char **,所以&amp; fgets()[0]是 一个char *,所以(为了避免倾倒yacc语法C的数字 out a语法ins和outary和postfix表达式 (虽然很有意思)),只需删除&#39;&amp;&#39;。

  • 在比较if(first ==&#34; \ n&#34;)中,first是char,所以make it if(first ==&#39; \ n&#39;)

所以......

#include <stdio.h>
int main(void){
  char input[100];
  char first;
  printf("Input something:\n>\n");
#if 0
  first = (char)(&fgets(input, 100, stdin)[0]);
  if(first == "\n"){
    // handle empty input here...
  }
#else
  first = (char)(fgets(input, 100, stdin)[0]);
  if(first == '\n'){
    // handle empty input here...
  }
#endif
}