繁体   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