簡體   English   中英

編譯器返回錯誤“ char *(int)”的間接尋址級別與“ int()”不同,即使返回的數據似乎與函數返回類型匹配

[英]Compiler returns error “char *(int)' differs in levels of indirection from 'int ()'” even though data returned seems to match function return type

我只是在學習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]);
}

您沒有為函數menutext()原型,因此C默認為int的返回類型。 這將導致printf()抱怨(您的情況是錯誤的),因為它期望它的第二個arg是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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM