gpt4 book ai didi

c - 如何从函数返回字符数组?然后在另一个函数中使用返回的字符?

转载 作者:行者123 更新时间:2023-11-30 15:26:43 24 4
gpt4 key购买 nike

    char * read_command()
{
char command[25];

char *input = malloc(sizeof(char) * 25);
printf("myRolodex Command: ");
scanf("%c", &command);
strcpy(input, command);
return input;
}

void evaluate_command(char command[250])
{
if (strcmp(command == 'I')==0)
{
printf("\nenterned i");
}
}

int main()
{
evaluate_command(read_command))
return 0;
}

我尝试这样做,但编译时得到:

rolodex.c: In function ‘read_command’:
rolodex.c:25: warning: format ‘%c’ expects type ‘char *’, but argument 2 has type ‘char (*)[25]’
rolodex.c: In function ‘evaluate_command’:
rolodex.c:32: warning: comparison between pointer and integer
rolodex.c:32: warning: passing argument 1 of ‘strcmp’ makes pointer from integer without a cast
/usr/include/string.h:143: note: expected ‘const char *’ but argument is of type ‘int’
rolodex.c:32: error: too few arguments to function ‘strcmp’
rolodex.c: In function ‘main’:
rolodex.c:43: warning: passing argument 1 of ‘evaluate_command’ from incompatible pointer type
rolodex.c:30: note: expected ‘char *’ but argument is of type ‘char * (*)()’
rolodex.c:43: error: expected ‘;’ before ‘)’ token
rolodex.c:43: error: expected statement before ‘)’ token

我应该让“read_command可以打印提示,然后从用户那里读取一个字符。它可能想在返回之前确保该命令是有效的命令。

evaluate_command 可以接受一个命令字符并决定它是哪个命令,然后执行适当的操作。”

最佳答案

编译器错误的解释。不过,您的代码还存在其他问题

 char * read_command()
{
char command[25];

char *input = malloc(sizeof(char) * 25);
printf("myRolodex Command: ");
scanf("%c", &command);

rolodex.c:25: warning: format ‘%c’ expects type ‘char ’, but argument 2 has type ‘char ()[25]’

所以这表明第二个参数的类型错误。您想将该字符放入 command 的第一个元素中。为此,您需要传递一个指向第一个字符的指针。您可以通过传递该字符的地址 -&command[0] 来完成此操作,尽管这与 command 相同。

        strcpy(input, command);
return input;
}

void evaluate_command(char command[250])
{
if (strcmp(command == 'I')==0)

rolodex.c:32: warning: comparison between pointer and integer

这一行有两个比较。 ==0strcmp 的返回值进行比较,返回一个整数。所以不可能是那个人。

对于另一个,我们将指向字符的指针(命令)与字 rune 字(对于 C 来说只是一个整数)进行比较。所以这是错误的。

rolodex.c:32: warning: passing argument 1 of ‘strcmp’ makes pointer from integer

比较的结果是(在 C 语言中)一个整数。但您需要将字符串传递给strcmp

rolodex.c:32: error: too few arguments to function ‘strcmp’

此外,strcmp 采用两个参数,那么这里发生了什么?您的意思大概是 strcmp(command, "I")

        {
printf("\nenterned i");
}
}

int main()
{
evaluate_command(read_command))

rolodex.c:43: warning: passing argument 1 of ‘evaluate_command’ from incompatible pointer type rolodex.c:30: note: expected ‘char *’ but argument is of type ‘char * (*)()’ rolodex.c:43: error: expected ‘;’ before ‘)’ token rolodex.c:43: error: expected statement before ‘)’ token

readcommand 是一个函数。您必须调用它(使用readcommand())

      return 0;
}

关于c - 如何从函数返回字符数组?然后在另一个函数中使用返回的字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27311662/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com