簡體   English   中英

錯誤:- 從不兼容的指針類型 [-Wincompatible-pointer-types] 傳遞“get_string”的參數 1

[英]ERROR :- passing argument 1 of 'get_string' from incompatible pointer type [-Wincompatible-pointer-types]

伙計們請告訴我的代碼有什么問題。 我已經添加了 cs50 庫和 header 文件,但似乎無法正確執行。 我是一個初學者,想知道你的建議。

代碼:-

#include <stdio.h>
#include <cs50.c>
#include <string.h>

int main(void)
{
    string s = get_string("Input:   ");
    printf("Output: ");
    int n = strlen(s);
    for( int i = 0; i < n; i++)
    {
        printf("%c", s[i]);
    }
    printf("\n");
}

錯誤:-

3.c: In function 'main':
3.c:7:27: warning: passing argument 1 of 'get_string' from incompatible pointer type [-Wincompatible-pointer-types]
    7 |     string s = get_string("Input:   ");
      |                           ^~~~~~~~~~~
      |                           |
      |                           char *
In file included from 3.c:2:
C:/msys64/mingw64/x86_64-w64-mingw32/include/cs50.c:78:28: note: expected 'char **' but argument is of type 'char *'        
   78 | string get_string(va_list *args, const char *format, ...)
      |                   ~~~~~~~~~^~~~
3.c:7:16: error: too few arguments to function 'get_string'
    7 |     string s = get_string("Input:   ");
      |                ^~~~~~~~~~
In file included from 3.c:2:
C:/msys64/mingw64/x86_64-w64-mingw32/include/cs50.c:78:8: note: declared here
   78 | string get_string(va_list *args, const char *format, ...)

cs50 文檔聲明您應該包括cs50.h ,而不是cs50.c https://cs50.readthedocs.io/libraries/cs50/c/#c.get_char https://cs50.readthedocs.io/libraries/cs50/c/#c.get_string

您需要在包含路徑中添加 header 文件。

在評論和之前的答案中已經說明,您不應包含cs50.c文件,而應僅包含cs50.h文件並將cs50.c文件鏈接到您的項目。

這通常是正確的,除非您有非常具體的理由采取不同的做法。

但是......通常這不應該導致我們在問題中看到的錯誤。 這是因為cs50.c文件本身包含cs50.h ,我們應該讓所有定義和聲明可見。

在這個特定的案例中,我們遇到了一些 CS50 庫的特定實現細節,這有點令人驚訝。 而且也沒有必要...

讓我們仔細看看header:

// cs50.h
string get_string(va_list *args, const char *format, ...) __attribute__((format(printf, 2, 3)));
#define get_string(...) get_string(NULL, __VA_ARGS__)

在這兩行之后,我們可以按照這個問題的作者的意圖使用get_stringstring s = get_string("Input: ");

並不是很明顯為什么有人會認為將 function 隱藏在具有相同名稱但參數不同的宏后面是一個好主意。 在大多數其他 API 中,function 的名稱與宏不同。 但是沒關系...

現在讓我們看一下 C 文件:

// cs50.c
#include "cs50.h"
...
#undef get_string
string get_string(va_list *args, const char *format, ...)
{
...
}

如果你自己編譯這個文件,一切都很好。 .c文件不需要宏,可以在定義 function 之前去掉它。

但是,如果您將其包含在您自己的文件中,而您應該在其中使用宏,則不再可能。 如果直接包含文件, undef會破壞 API。

這強調了您應該只包含標題的事實。 它們應該被包括在內,並且是相應地制作的。 正如我們所見,保存實現的.c文件不一定是這樣制作的……

附帶說明:這個#undef根本沒有必要。 你可以簡單地這樣做:

// cs50.c
#include "cs50.h"
...
string (get_string)(va_list *args, const char *format, ...)
{
...
}

使用封閉()標識符get_string不再匹配宏get_string()並且不進行替換。 這甚至允許直接包含.c文件。

也許他們故意選擇這種方式是為了防止包含 c 文件,但我不會打賭。

暫無
暫無

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

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