gpt4 book ai didi

c - 将 'void'传递给不兼容类型 'const char *'的参数?

转载 作者:行者123 更新时间:2023-12-02 10:56:58 24 4
gpt4 key购买 nike

当我运行以下代码时,在此行上收到“将'void'传递给不兼容类型'const char *'的参数”错误:

int result = strcmp(lowerCase(input), answers[i]);

错误所在的代码是:
for (int i = 0; i <= sizeof(questions); i++)
{
printf("%s", questions[i]);
scanf("%s", input);

int result = strcmp(lowerCase(input), answers[i]);
if (result == 0)
{
score++;
}
}

而lowerCase定义为:
void lowerCase(char s[]) {

int c = 0;

while (s[c] != '\0') {

if (s[c] >= 'a' && s[c] <= 'z') {

s[c] = s[c] + 32;

}

c++;
}
}

整个代码是:
#include <stdlib.h>
#include <stdio.h>
#include <string.h> // strcmp() prototype is in here.
#include <ctype.h>

char *questions[3];
char *answers[3];

void fillQuestions(void);
void fillAnswers(void);

void lowerCase(char []);

int main(int argc, const char * argv[])
{
fillQuestions();
fillAnswers();

char input[80];
int score = 0;

for (int i = 0; i <= sizeof(questions); i++)
{
printf("%s", questions[i]);
scanf("%s", input);


int result = strcmp(lowerCase(input), answers[i]);
if (result == 0)
{
score++;
}
}
printf("\n\tSCORE: %d\n\n", score);

return 0;
}

void fillQuestions()
{
questions[0] = "The famous basketball player Dr. J original name is what?";

}

void fillAnswers()
{
answers[0] = "Julius Erving";

}

void lowerCase(char s[]) {

int c = 0;

while (s[c] != '\0') {

if (s[c] >= 'a' && s[c] <= 'z') {

s[c] = s[c] + 32;

}

c++;
}

}

我正在使用XCode 11.3。

最佳答案

编译器投诉

您不能将不返回值的函数返回的值传递给另一个函数(因此,有关voidconst char *的错误消息)。

因为lowerCase()不返回值(其返回类型为void),所以您不能执行以下操作:

strcmp(lowerCase(input), answers[i]);

您将使用:
lowerCase(input);
int result = strcmp(input, answers[i]);

或者,修改 lowerCase(),使其返回 char *并以 return s;结束(然后您无需将调用更改为 strcmp())。

重写 lowerCase()
由于您包含 <ctype.h>,因此您可以编写:

void lowerCase(char s[])
{
int c = 0;
while (s[c] != '\0') {
if (isupper((unsigned char)s[c])) {
s[c] = tolower((unsigned char)s[c]);
}
c++;
}
}

要么:

char *lowerCase(char s[])
{
for (int c = 0; s[c] != '\0'; c++)
s[c] = tolower((unsigned char)s[c]);
return s;
}

如果普通 char是带符号类型,则必须进行强制类型转换。 functions from <ctype.h> 采用 int,它是EOF或转换为 unsigned char的字符的值。

不必测试字符是否为小写; tolower()函数保留所有大写形式不变的内容-以及使用这些函数的其他优点。

其他问题

您在 questionsanswers中有3个元素,但每个元素只初始化一个。循环到索引1时,将获得空指针,因此在错误消息中为 address = 0x0。您尝试从空指针读取;这样做通常会导致崩溃。

另外, sizeof(questions)几乎可以肯定是24 —存储三个64位指针所需的字节数。您需要 sizeof(questions) / sizeof(questions[0])作为循环限制-如果您添加了另外两个问题和答案。

因为您将输入转换为所有小写字母,所以您将永远不会获得与答案匹配的输入(大小写混合)。

答案字符串存储在字符串文字中。如果您尝试使用 lowerCase()修改答案,则会崩溃,因为字符串文字存储在只读内存中。

关于c - 将 'void'传递给不兼容类型 'const char *'的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60628719/

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