简体   繁体   中英

Why is printing a C array showing non-contiguous addresses?

I read that Array bucket values are stored in contiguous memory locations. I was trying to print a character array's memory location on my 64 bit mac as

char str1[] = "Hell";
    printf("%p:%lu:%c, %p:%lu:%c, %p:%lu:%c, %p:%lu:%c", str1[0], str1[0], str1[0], str1[1], str1[1], str1[1], str1[2], str1[2], str1[2], str1[3], str1[3], str1[3]);

and the result I got was

0x48:72:H, 0x65:101:e, 0x7fff0000006c:140733193388140:l, 0x7fff0000006c:108:l

This doesn't looks like a contiguous memory addresses to me, considering the size of a char is 1 byte . Please help me understand this if I am learning it wrong.

The arguments in your printf statement are incorrect.

If you meant to print the addresses in decimal, here is what you should write:

char str1[] = "Hell";
printf("%p:%lu:%c, %p:%lu:%c, %p:%lu:%c, %p:%lu:%c\n",
       (void*)&str1[0], (unsigned long)&str1[0], str1[0],
       (void*)&str1[1], (unsigned long)&str1[1], str1[1],
       (void*)&str1[2], (unsigned long)&str1[2], str1[2],
       (void*)&str1[3], (unsigned long)&str1[3], str1[3]);

Note however that converting a pointer to an unsigned long might loose information as the size of unsigned long might be smaller than that of a char* (it is on Windows 64-bit);

If you meant to output the characters in decimal and as characters, the format should be %d and the code changed to:

char str1[] = "Hell";
printf("%p:%d:%c, %p:%d:%c, %p:%d:%c, %p:%d:%c\n",
       (void*)&str1[0], str1[0], str1[0],
       (void*)&str1[1], str1[1], str1[1],
       (void*)&str1[2], str1[2], str1[2],
       (void*)&str1[3], str1[3], str1[3]);

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