簡體   English   中英

為什么這個對 sprintf_s() 的調用有效,我怎樣才能在我的計算機上使它工作?

[英]Why does this call to sprintf_s() work, and how can I make this work on my computer?

我是一個沒有經驗的學生,這是我們 C++ 編程作業的已發布解決方案的一部分。 但它不能在我的電腦上編譯,我需要幫助理解為什么。 我遇到的第一條錯誤消息是在 sprintf_s() 說“標識符 'sprintf_s' 未聲明”,我認為這是因為我正在運行 linux 並且 sprintf_s() 不是標准庫函數。 因此,我嘗試將其替換為 snprintf() 並且原始錯誤消息消失了(但請讓我知道這是否不正確,我的更改已在原始行上方注釋掉)。

更改后,我收到錯誤消息“'const char *'類型的參數與'size_t'類型的參數不兼容”和“'float'與'const char *'類型的參數不兼容”。 我知道 sprintf_s() 和 snprintf() 的參數都是(char *str, size_t size, const char *format, ...)所以我認為這個錯誤是有道理的,因為傳遞的 arguments 缺少大小。 但是,如果必須有大小的參數,那么將其設置為 128 是否正確? 為什么在我老師的用於 sprintf_s() 的 Windows 機器上沒有這個論點,但在用於 snprintf() 的 Linux 上卻不行? 另外,他使用的是 Visual Studio,我使用的是 Visual Studio Code。

整個 function 如下圖所示。 如果您知道我在編譯應該是可行的解決方案時可能遇到問題的另一個原因,請告訴我!

bool myNode::isAccessible()
{
    return isAccessible(x, y);
}
myNode::myNode(const float location[3])
{
    x = (location[0] > 0.0) ? (int)floor(location[0] / SCALE + 0.5f) : (int)ceil(location[0] / SCALE - 0.5f);
    y = (location[1] > 0.0) ? (int)floor(location[1] / SCALE + 0.5f) : (int)ceil(location[1] / SCALE - 0.5f);
    if (isAccessible(x, y)) return;
    int originalX = x, originalY = y;
    for (int a = -1; a <= 1; a++)
        for (int b = -1; b <= 1; b++) {
            if (a == 0 && b == 0) continue;
            x = originalX + a;
            y = originalY + b;
            if (isAccessible(x, y)) return;
        }
    char buffer[128];
    //snprintf(buffer, "***AStarNode: could not find any isAccessible node for (%f, %f, %f)***", location[0], location[1], location[2]);
    sprintf_s(buffer, "***AStarNode: could not find any isAccessible node for (%f, %f, %f)***", location[0], location[1], location[2]);
    controlPanel->addMessage(buffer);
}

錯誤"argument of type 'const char *' is incompatible with parameter of type 'size_t'"並且以下錯誤來自於snprintf缺少緩沖區大小參數。

snprintf的正確調用是:

snprintf(buffer, sizeof buffer, "***AStarNode: could not find any isAccessible node for (%f, %f, %f)***", location[0], location[1], location[2]);

暫無
暫無

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

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