1

我似乎无法在没有错误的情况下运行这个名为 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

我对取消引用和我的语法缺少什么?

4

2 回答 2

2

您需要重新安排此线路上的呼叫:

inbuf = atoi(factorial(inbuf*));

应该

int answ = factorial(atoi(inbuf));

*假设所有其他代码都有效,但我认为您需要将 inbuf 的声明从更改char *inbuf[MSGSIZE];char inbuf[MSGSIZE];

于 2011-04-12T19:51:37.573 回答
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)));
于 2011-04-12T20:10:27.087 回答