[英]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.