编译器返回错误 "char *(int)' 与 'int ()' 的间接级别不同“即使返回的数据似乎与函数返回类型匹配

标签 c arrays function pointers

我刚刚学习 C,这是我第一次使用 stackoverflow 所以我不确定问这个问题是否合适,因为与这里的其他人相比它似乎微不足道,但我找到了这篇文章教科书中的代码,当我尝试在 Visual Studio 中编译时,我得到了这个:

**error C2040: 'menutext' : 'char *(int)' differs in levels of indirection from 'int ()'**

老实说,我看过代码,但不明白为什么编译器会报错。我真的需要一些帮助。这是代码:

/*********************************************************/
/* */
/* MENU : program which prints out a menu */
/* */
/*********************************************************/
main ()
{ 
  int str_number;
  for (str_number = 0; str_number < 13; str_number++)
  {
    printf ("%s",menutext(str_number));
  }
}
/*********************************************************/
char *menutext(int n) /* return n-th string ptr */
{
  static char *t[] =
  {
    " -------------------------------------- \n",
    " | ++ MENU ++ |\n",
    " | ~~~~~~~~~~~~ |\n",
    " | (1) Edit Defaults |\n",
    " | (2) Print Charge Sheet |\n",
    " | (3) Print Log Sheet |\n",
    " | (4) Bill Calculator |\n",
    " | (q) Quit |\n",
    " | |\n",
    " | |\n",
    " | Please Enter Choice |\n",
    " | |\n",
    " -------------------------------------- \n"
  };
  return (t[n]);
}

最佳答案

您没有为函数制作原型(prototype) menutext()因此 C 默认返回类型为 int .这将导致 printf()提示(在你的情况下是错误的)因为它期望它的第二个参数是 char * 类型, 不是 int 类型.

在对 main() 的调用上方添加以下两行

#include <stdio.h>   /* Needed for the call to printf() */
char *menutext(int); /* Prototype for menutext() */

此外,main()应该总是返回类型 int如果你不打算传递任何参数,你应该传递 void明确说明该意图。因此,您的代码的上半部分应如下所示:

#include <stdio.h>   /* Needed for the call to printf() */ 
char *menutext(int); /* Prototype for menutext() */

int main(void)
{
   /* main code here */
   return 0;
}

关于编译器返回错误 "char *(int)' 与 'int ()' 的间接级别不同“即使返回的数据似乎与函数返回类型匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4418170/

相关文章:

c - 我不明白这个程序是做什么的,它是一个递归程序

c - 如何在 Oracle 中对 XMLType 列使用 OCI?

c - 错误 : expected expression; use of undeclared identifier

c++ - 链表加法/减法函数正在改变参数的值?

java - 换行后字节不相等

java - 通过数组搜索时出现 NullPointerException 错误

java - 这条语句的返回值是多少

c - 从文件中单独读取单词

networking - 在调用 recvfrom() 时使用什么字节序来存储信息

c - C 程序中的搜索和排序?