简体   繁体   English

扫描和打印 uint64_t (long long unsigned int) 时遇到问题

[英]Having trouble scanning and printing uint64_t (long long unsigned int)

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

int main(void)
{
    uint64_t *ptr = malloc(sizeof(uint64_t));
    scanf("%llu",&ptr);
    printf("%llu\n", *ptr);
    free(ptr);
}

The compiler says that编译器说

mod_5_working.c:9:14: error: unknown conversion type character 'l' in format [-Werror=format=]
     scanf("%llu",&ptr);
              ^
mod_5_working.c:9:11: error: too many arguments for format [-Werror=format-extra-args]
     scanf("%llu",&ptr);

I've tried using %u but it says that I should use %llu .我试过使用%u但它说我应该使用%llu

  • scanf("%llu",&ptr); is senseless, like the compiler tells you, you are taking the address of a pointer.毫无意义,就像编译器告诉您的那样,您正在获取指针的地址。

  • uint64_t doesn't necessarily correspond to unsigned long long . uint64_t不一定对应于unsigned long long Some 64 bit systems use unsigned long for 64 bit numbers.一些 64 位系统对 64 位数字使用unsigned long整数。

The correct, portable specifiers to use when scanning/printing uint64_t is SCNu64 and PRIu64 from inttypes.h:扫描/打印uint64_t时使用的正确、可移植的说明符是 inttypes.h 中的SCNu64PRIu64

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

int main(void)
{
    uint64_t *ptr = malloc(sizeof(uint64_t));
    scanf("%"SCNu64, ptr);
    printf("%"PRIu64"\n", *ptr);
    free(ptr);
}

scanf expects a pointer, not a pointer to a pointer. scanf需要一个指针,而不是指向指针的指针。 Simply pass the pointer to scanf , no need to & it.只需将指针传递给scanf ,无需&它。 Also you should always check the return value of malloc for errors.此外,您应该始终检查malloc的返回值是否有错误。

uint64_t *ptr = malloc(sizeof(uint64_t));
if (!ptr)
    return -1; /* Maybe handle it better */

scanf("%" SCNu64, ptr);
printf("%" PRIu64 "\n", *ptr);

free(ptr);

Edit: It's a better practice to use SCNu64 and PRIu64 (from <inttypes.h> ) to make it portable and accurate.编辑:使用SCNu64PRIu64 (来自<inttypes.h> )使其可移植和准确是一种更好的做法。

Use the matching specifier.使用匹配说明符。

#include <stdio.h>
#include <inttypes.h> /* Format conversions for exact-width types */

scanf("%" SCNu64, ptr);  // No &.
printf("%" PRNu64 "\n", *ptr);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM