[英]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);
}
編譯器說
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);
我試過使用%u
但它說我應該使用%llu
。
scanf("%llu",&ptr);
毫無意義,就像編譯器告訴您的那樣,您正在獲取指針的地址。
uint64_t
不一定對應於unsigned long long
。 一些 64 位系統對 64 位數字使用unsigned long
整數。
掃描/打印uint64_t
時使用的正確、可移植的說明符是 inttypes.h 中的SCNu64
和PRIu64
:
#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
需要一個指針,而不是指向指針的指針。 只需將指針傳遞給scanf
,無需&
它。 此外,您應該始終檢查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);
編輯:使用SCNu64
和PRIu64
(來自<inttypes.h>
)使其可移植和准確是一種更好的做法。
使用匹配說明符。
#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.