![](/img/trans.png)
[英]warning: field width specifier '*' expects argument of type 'int', but argument 2 has type 'size_t' {aka 'long unsigned int'}
[英]warning: format ‘%d’ expects argument of type ‘int *’, but argument 3 has type ‘uint8_t * {aka unsigned char *}
我遇到了一個問題,上面寫着:
warning: format '%d' expects argument of type 'int *', but argument 3 has type 'uint8_t * {aka unsigned char *}
我不確定為什么會這樣,因為我認為 int 和 uint8_t 是可以互換的。
這是我的代碼:
uint8_t** fileRead(char* file, int* pointer) {
FILE* file = fopen(file, "r");
int count = 0;
pointer = &count;
fscanf(file, "%d", &count); //this retrieves a single integer
uint8_t** result = (uint8_t**) malloc(*pointer * sizeof(uint8_t*));
while (file != NULL) {
for (uint8_t i = 0; i < *pointer; i++) {
uint8_t* a = (uint8_t*) malloc(sizeof(uint8_t));
uint8_t* b = (uint8_t*) malloc(sizeof(uint8_t));
uint8_t* c = (uint8_t*) malloc(sizeof(uint8_t));
fscanf(file, "%d", a);
fscanf(file, "%d", b);
fscanf(file, "%d", c);
if (a == NULL || b == NULL || c == NULL) {
uint8_t* npointer = NULL;
fclose(file);
free(result);
return NULL;
} else {
result[i][0] = *a;
result[i][1] = *b;
result[i][2] = *c;
free(a);
free(b);
free(c);
}
}
}
return result;
}
並且錯誤發生在以下幾行:
fscanf(file, "%d", a);
fscanf(file, "%d", b);
fscanf(file, "%d", c);
非常感謝你提前
使用"%hhu"
作為格式說明符而不是"%d"
。
我認為 int 和 uint8_t 是可以互換的。
它們不是 - int
(有符號或無符號)必須至少為16 位寬(可能更寬,但不能更窄) 1 。 uint8_t
,顧名思義,是 8 位寬。
您需要使用格式說明符%hhu
將數值讀入uint8_t
或unsigned char
object。
int
必須能夠表示至少在[-32767..32767]
范圍內的所有值。 這需要至少 16 位。 一些架構(我從未使用過)具有“填充位”,它們會影響字長,但不用於存儲值。 因此,例如,您可以有一台 9 位機器和 18 位字,但該系統上的實現仍然可以選擇僅使用 16 位來表示一個“int”值——其中兩個位根本沒有被使用. 要使用(f)scanf
將 integer 讀入unsigned char
,您需要"%hhu"
。
打印時,您可以避免使用%d
作為格式說明符,因為uint8_t
在傳遞給像printf
這樣的可變參數 function 時會被提示為int
。 然而,指針不會發生這種提升,這是scanf
對大多數格式說明符所期望的。
如您所見, scanf
的%d
格式說明符需要一個int *
。 在您可能遇到的大多數系統上,一個int
是 4 個字節。 因此,當scanf
取消引用您為%d
提供的指針以寫入值時,它將寫入 4 個字節。 如果你傳入一個uint8_t *
這會中斷,因為這種類型只占用 1 個字節。 通過使用%d
, scanf
會認為您正在傳遞一個int
的地址並寫入 4 個字節,即在給定變量末尾之后的 3 個字節。 這樣做會調用未定義的行為。
要解決此問題,請將格式說明符更改為%hhu
,它需要一個unsigned char *
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.