我對memchr()in的作業技術有點困惑C。我觀察了不同的實作memchr()并發現它首先將字符或數字轉換為unsigned char型別,然后逐位元組搜索陣列。
我有兩個問題:
1.如果它將任何內容轉換為unsigned char那么它如何比較大小大于 的數字 unsigned char,例如int型別。2.如果它逐位元組比較并回傳然后回傳字符第一次出現的地址,那么假設我想0x8在一個陣列中搜索。
#include <stdio.h>
#include <string.h>
int main(void)
{
const int arr[5] = {0x1021, 0x8988, 0x706, 0x50, 0x22};
int * ptr;
ptr = memchr(arr, 0x89, sizeof(arr));
printf("arr:%p ptr:%p\n", arr, ptr);
return 0;
}
它應該回傳陣列的第 3 個位元組的地址,作為0x89與第0x89887 個位元組的陣列元素的第一個位元組memchr()匹配的匹配位元組,(unsigned char)而不是int型別。
假設:int是 4 個位元組,unsigned char是 1 個位元組。
uj5u.com熱心網友回復:
它沒有。
memchr只能搜索可由 表示的值unsigned char。如果您提供一個
ints陣列作為 的第一個引數memchr,那么它將unsigned char在每個的物件表示中查找您作為第二個引數提供的值int。a 的物件表示
uint32_t是 的兩個成員之間的對應關系union { uint32_t v; uint8_t r[4]; } u;它是實作定義的,但幾乎總是這兩個之一:- 大端:
v === r[0] << 24 | r[1] << 16 | r[2] << 8 | r[3] - 小端:
v === r[3] << 24 | r[2] << 16 | r[1] << 8 | r[0]
an 的物件表示
int32_t是上面加上如何表示負數的規則。的物件表示int是這兩件事加上 的實際大小int。- 大端:
您展示的示例代碼,
const int arr[5] = {0x1021, 0x8988, 0x706, 0x50, 0x22};
int *ptr = memchr(arr, 0x89, sizeof(arr));
是,假設int和int32_t是相同型別,并假設小端物件表示,我們不關心負數是如何表示的,因為這里的所有數字都是正數,等價于
const uint8_t arr[20] = {
0x21, 0x10, 0x00, 0x00,
0x88, 0x89, 0x00, 0x00,
0x06, 0x07, 0x00, 0x00,
0x50, 0x00, 0x00, 0x00,
0x22, 0x00, 0x00, 0x00,
};
int *ptr = memchr(arr, 0x89, sizeof(arr));
您可以看到要搜索的值 0x89 出現在距第二個陣列開頭的偏移量 5 處。
(注意: 的型別ptr應該是uint8_t *,不是int *。回傳的指標memchr不一定是指向int(也不是除 之外的任何其他東西unsigned char)的有效指標。)
uj5u.com熱心網友回復:
只需添加幾行代碼,您就可以輕松找到答案,而不是問這個問題。如果你真的想學習編程,你需要自己做。
int main(void)
{
const int arr[5] = {0x1021, 0x8988, 0x706, 0x50, 0x22};
int * ptr;
unsigned char *ucp = arr;
for(size_t i = 0; i < sizeof(arr); i )
{
printf("Byte no: zu = 0xhhx, %s\n", i, ucp[i], ucp[i] == 0x89 ? " <<<----" : "");
}
ptr = memchr(arr, 0x89, sizeof(arr));
printf("arr:%p ptr:%p diff = %zd\n", (void *)arr, (void *)ptr, (ptrdiff_t)ptr - (ptrdiff_t)arr);
}
和輸出:
Byte no: 00 = 0x21,
Byte no: 01 = 0x10,
Byte no: 02 = 0x00,
Byte no: 03 = 0x00,
Byte no: 04 = 0x88,
Byte no: 05 = 0x89, <<<----
Byte no: 06 = 0x00,
Byte no: 07 = 0x00,
Byte no: 08 = 0x06,
Byte no: 09 = 0x07,
Byte no: 10 = 0x00,
Byte no: 11 = 0x00,
Byte no: 12 = 0x50,
Byte no: 13 = 0x00,
Byte no: 14 = 0x00,
Byte no: 15 = 0x00,
Byte no: 16 = 0x22,
Byte no: 17 = 0x00,
Byte no: 18 = 0x00,
Byte no: 19 = 0x00,
arr:0x7fffc2747900 ptr:0x7fffc2747905 diff = 5
我想現在答案已經很明顯了。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/331904.html
上一篇:C中的霍夫變換有問題
