c - 为什么 gets(stdin) 返回一个整数?和其他错误

标签 c compiler-errors standard-library gets

<分区>

我是 C 编程的新手(尽管我有 Java 经验)。阅读一些教程后,我决定开始解决 Coderbyte 上的编码挑战。 .

我尝试的第一个挑战是 this one :

Challenge

Have the function FirstFactorial(num) take the num parameter being passed and return the factorial of it. For example: if num = 4, then your program should return (4 * 3 * 2 * 1) = 24. For the test cases, the range will be between 1 and 18 and the input will always be an integer.

Sample Test Cases

Input: 4
Output: 24

Input: 8
Output: 40320

我的解决方案:

#include <stdio.h>

void FirstFactorial(int num[]) {

  int i = num -1;

  for(i ; i > 0; i--) {
    num = num * i;
    printf("%d",i);
  }

  printf("\t %d", num);
}

int main(void) {

  // disable stdout buffering
  setvbuf(stdout, NULL, _IONBF, 0);

  // keep this function call here
  FirstFactorial(gets(stdin));
  return 0;

}

输入参数的值:8

错误信息:

main.c: In function 'FirstFactorial':
main.c:5:11: warning: initialization makes integer from pointer without a cast [-Wint-conversion]
   int i = num -1;
           ^~~
main.c:8:15: error: invalid operands to binary * (have 'int *' and 'int')
     num = num * i;
               ^
main.c: In function 'main':
main.c:23:18: warning: passing argument 1 of 'FirstFactorial' makes pointer from integer without a cast [-Wint-conversion]
   FirstFactorial(8);
                  ^
main.c:3:6: note: expected 'int *' but argument is of type 'int'
 void FirstFactorial(int num[]) {
      ^~~~~~~~~~~~~~

exit status 1

所以好像有几个问题,我有几个问题:

  1. 我从未听说过gets(stdin)。我查了一下gets() ,并且 glibc 文档说该函数返回一个 char*。如何将它传递给采用 int 的函数?

  2. 看起来像

    int i = num -1;
    

    正在将 i 初始化为 4 而不是 7。为什么?

  3. for 循环似乎正确地递减了 i(i = 7、6、5、4、3、2、1)。但是这个声明:

    num = num * i;
    

    正在生成错误。它有什么问题?它看起来像一个普通的乘法。

最佳答案

为了 future 的访问者:

这是对 Coderbytes 为“方便”而使用的语言的可怕滥用。 gets(stdin) 一开始就不应该起作用:类型不起作用。

实际发生的事情是 Coderbytes 在发送之前盲目地用您作为输入提供的文字字符串查找并替换 gets(stdin) 的第一个实例你的代码到编译器。这甚至不是预处理器宏,而是对源代码的盲目替换。

因此,虽然您在现实中永远不应该这样做,但在 Coderbytes 上这是一个必要的邪恶:这似乎是唯一支持将输入输入到您的程序中的方式。

Source


此外,如果您想要一些娱乐,请尝试清除所有其他内容并将其放入 Coderbytes:

int main(){
    printf("%s", "This is a literal string containing gets(stdin) along with other words");
}

您会看到替换甚至发生在字符串文字中!

关于c - 为什么 gets(stdin) 返回一个整数?和其他错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49871653/

相关文章:

scala - 消除重载方法定义的歧义

c++ - C++ 1z中的编译时反射?

c++ - 是否有任何 100% C++11 兼容的 std 实现?

c - fwprintf 不输出宽字符

c - 选择最大数并对其进行平方或立方时结果不正确

c - Strcmp 生成核心转储

c - 如何阻止 GCC 破坏我的 NEON 内在函数?

c - 函数头中struct *和struct **的区别

c++ - 错误 : no match for ‘operator<<’

compilation - 在树莓派上编译p0sixspwn的问题