简体   繁体   中英

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");
}

Suppose I have two functions above, and I use main function to test my functions:

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);
}

I got the following results in my terminal:

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

Can someone tell me why I got the result? I understand the second function, but I have no idea why I got 39 30 00 00 7b 00 00 00 17 00 00 00 2d 00 00 00 01 00 00 00 for the first function. Actually I know the number sequence above are hexadecimal decimal for 12345 , 123 , 23 , 45 , 1 . However, I have no idea: start[i] pointer doesn't point to the whole number such as 12345 or 123 in the first function. Instead, the start[0] just point to the least significant digit for the first number 12345 ? Can someone help me explain why these two functions are different?

12345 is 0x3039 in hex. because int is 32bits on your machine it will be represented as 0x00003039 . then because your machine is little endian it will be represented as 0x39300000 . you can read more about Big and Little endian on: https://www.cs.umd.edu/class/sum2003/cmsc311/Notes/Data/endian.html

the same applies for other results.

On your platform, sizeof(int) is 4 and your platform uses little endian system. The binary representation of 12345 using a 32-bit representation is:

00000000 00000000 00110000 00111001

In a little endian system, that is captured using the following byte sequence.

00111001 00110000 00000000 00000000

In hex, those bytes are:

39 30 00 00

That's what you are seeing as the output corresponding to the first number.

You can do similar processing of the other numbers in the array to understand the output corresponding to them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM