user144600 user144600 - 1 year ago 71
Linux Question

what is the differnce of 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

void show_integer(int* p,size_t len){
size_t i;
printf(" %d",p[i]);

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

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?

Answer Source

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:

the same applies for other results.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download