[英]What is the difference between these two C functions in terms of handling memory?
typedef unsigned char *byte_pointer;
void show_bytes(byte_pointer start, size_t len) {
size_t i;
for (i = 0; i < len; i++)
printf(" %.2x", start[i]); //line:data:show_bytes_printf
printf("\n");
}
void show_integer(int* p,size_t len){
size_t i;
for(i=0;i<len;i++){
printf(" %d",p[i]);
}
printf("\n");
}
假設我上面有兩個函數,並且我使用main函數來測試我的函數:
int main(int argc, char *argv[])
{
int a[5]={12345,123,23,45,1};
show_bytes((byte_pointer)a,sizeof(a));
show_integer(a,5);
}
我在終端中得到以下結果:
ubuntu@ubuntu:~/OS_project$ ./show_bytes
39 30 00 00 7b 00 00 00 17 00 00 00 2d 00 00 00 01 00 00 00
12345 123 23 45 1
有人可以告訴我為什么我得到結果嗎? 我了解第二個功能,但是我不知道為什么我要為第一個功能獲得39 30 00 00 7b 00 00 00 17 00 00 00 2d 00 00 00 01 00 00 00
。 事實上,我知道上面的數字序列是十六進制小數為12345
, 123
, 23
, 45
, 1
。 但是,我不知道: start[i]
指針沒有指向第一個函數中的整數,例如12345
或123
。 相反, start[0]
僅指向第一個數字12345
的最低有效位? 有人可以幫我解釋一下這兩個功能為何不同嗎?
12345
是十六進制的0x3039
。 因為int在您的計算機上是32位,所以它將表示為0x00003039
。 然后,因為您的計算機是0x39300000
字節序,它將被表示為0x39300000
。 您可以在以下網站上了解有關大小尾數的更多信息: https : //www.cs.umd.edu/class/sum2003/cmsc311/Notes/Data/endian.html
其他結果也一樣。
在您的平台上, sizeof(int)
為4
並且您的平台使用Little Endian系統。 使用32位表示形式的12345
的二進制表示形式是:
00000000 00000000 00110000 00111001
在小端系統中,使用以下字節序列捕獲該字節。
00111001 00110000 00000000 00000000
以十六進制表示,這些字節是:
39 30 00 00
這就是與第一個數字相對應的輸出。
您可以對數組中的其他數字執行類似的處理,以了解與它們相對應的輸出。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.