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

Passing 'void' to parameter of incompatible type 'const char *'?

当我 运行 下面的代码时,我在这一行收到 "Passing 'void' to parameter of incompatible type '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++;
    }
}

小写定义为:

void lowerCase(char s[]) {

   int c = 0;

   while (s[c] != '[=14=]') {

      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] != '[=15=]') {

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

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

      }

      c++;
   }

}

我正在使用 XCode 11.3.

编译器投诉

您不能将值 return 由一个没有 return 值的函数传递给另一个函数(因此有关 void 和 [=15 的错误消息=]).

因为lowerCase()不是return一个值(它的return类型是void),你不能做:

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

你会使用:

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

或者,修改 lowerCase() 使其 return 成为 char * 并以 return s; 结束(然后您不需要将调用更改为 strcmp()).


重写lowerCase()

因为你包含 <ctype.h>,你可以写:

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

或:

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

如果 plain 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() 修改答案,您会遇到崩溃,因为字符串文字存储在只读内存中。