我似乎无法运行这个名为factorial()的函数而不会出现错误。
首先,如果我有inbuf = atoi(factorial(inbuf));
,gcc会吐出来,
main.c:103: warning: passing argument 1 of ‘factorial’ makes integer from pointer without a cast
如果我将其更改为inbuf = atoi(factorial(inbuf*));
,gcc会吐出来,
main.c:103: error: expected expression before ‘)’ token
相关代码:
int factorial(int n)
{
int temp;
if (n <= 1)
return 1;
else
return temp = n * factorial(n - 1);
} // end factorial
int main (int argc, char *argv[])
{
char *inbuf[MSGSIZE];
int fd[2];
# pipe() code
# fork() code
// read the number to factorialize from the pipe
read(fd[0], inbuf, MSGSIZE);
// close read
close(fd[0]);
// find factorial using input from pipe, convert to string
inbuf = atoi(factorial(inbuf*));
// send the number read from the pipe to the recursive factorial() function
write(fd[1], inbuf, MSGSIZE);
# more code
} // end main
我在解除引用和语法方面缺少什么?
答案 0 :(得分:2)
你需要在这一行重新安排你的电话:
inbuf = atoi(factorial(inbuf*));
应该是
int answ = factorial(atoi(inbuf));
*假设所有其他代码都有效,但我认为您需要将inbuf的声明从char *inbuf[MSGSIZE];
更改为char inbuf[MSGSIZE];
答案 1 :(得分:1)
首先,将 inbuf 更改为:char inbuf[MSGSIZE];
其次,您需要将 inbuf 转换为 int 以将其传递给factorial()
。 atoi()
正是这样做的。然后,您获取此操作的结果并将其转换回字符串并将其分配给 inbuf :这就是sprintf()
的原因。
// find factorial using input from pipe, convert to string
sprintf(inbuf, "%d", factorial(atoi(inbuf)));