gpt4 book ai didi

c - scanf 无法识别格式 %zu

转载 作者:行者123 更新时间:2023-11-30 16:05:55 25 4
gpt4 key购买 nike

我有以下代码:

#include <stdio.h>
#include <stdlib.h>

int compare(const void* a, const void* b)
{
const int* x = a, *y = b;
if (*x < *y)
return -1;
else if (*x == *y)
return 0;
else
return 1;
}

int main()
{
size_t n;
printf("Enter number of numbers: ");
scanf("%zu", &n); //<-- warnings here
int numbers[n];
for (size_t i = 0; i < n; i++)
{
printf("Enter number #%zu: ", i + 1); //NO warning here, printf works as expected
scanf("%d", &numbers[i]);
}
qsort(numbers, n, sizeof *numbers, compare);
for (size_t i = 0; i < n; i++)
printf("%d ", numbers[i]);
printf("\n");
system("pause"); //don't comment for this, I know it's bad
}

我从 GCC 编译器收到 2 条警告:

warning: unknown conversion type character 'z' in format [-Wformat=]
warning: too many arguments for format [-Wformat-extra-args]

我已将 GCC 设置为 C11。谁能帮我理解为什么我会得到这个?

编辑:我忘了提及,即使有这些警告,我的代码仍然有效,但是对我来说很奇怪,变量 n 似乎没有从 scanf 获取其值

最佳答案

but I don't know how to check my compiler version

常见测试涉及__STDC__、__STDC_VERSION__。像这样的东西:

#if defined __STDC__
#if defined __STDC_VERSION__ && __STDC_VERSION__ > 201710
// New
#error Time to update this code
#elif defined __STDC_VERSION__ && __STDC_VERSION__ >= 201710
#define CVERSION 2017
#elif defined __STDC_VERSION__ && __STDC_VERSION__ >= 201112
#define CVERSION 2011
#elif defined __STDC_VERSION__ && __STDC_VERSION__ >= 199901
#define CVERSION 1999
#elif defined __STDC_VERSION__ && __STDC_VERSION__ >= 199409
#define CVERSION 1994
#else
#define CVERSION 1989
#else
// Pre-standard C
#define CVERSION 1972
#endif
<小时/>

“警告:格式 [-Wformat=] 中未知的转换类型字符 'z'”意味着使用旧的编译器。由于"%zu"是在C99中引入的。可能的条件编译。

size_t n;
printf("Enter number of numbers: ");
#if defined __STDC__ && defined __STDC_VERSION__ && __STDC_VERSION__ >= 199901
scanf("%zu", &n);
#else
unsigned long t;
scanf("%lu", &t);
n = t;
#endif

或者使用顶部的代码:

#if CVERSION >= 1999
scanf("%zu", &n);
#else
unsigned long t;
scanf("%lu", &t);
n = t;
#endif

关于c - scanf 无法识别格式 %zu,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60125794/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com