打印整型变量占用的所有字节地址

Print the addresses of all the bytes occupied by an integer variable

这是代码 -

#include <stdio.h>
int main()
{
    char character_1 = '0';
    int integer_1 = 12321;
    char character_2 = '1';
    char character_3 = '2';

    printf("Integer occupies %zu byte(s) of space.\n",sizeof(int));
    printf("Address of Integer 1: %p\n",(void*)&integer_1);
    printf("\n");

    printf("Character occupies %zu byte(s) of space.\n",sizeof(char));
    printf("Address of Character 1: %p\n",(void*)&character_1);
    printf("Address of Character 2: %p\n",(void*)&character_2);
    printf("Address of Character 3: %p\n",(void*)&character_3);
    printf("\n");
    return 0;
}

并且,生成的输出 -

Integer occupies 4 byte(s) of space.
Address of Integer 1: 000000000061FE18

Character occupies 1 byte(s) of space.
Address of Character 1: 000000000061FE1F
Address of Character 2: 000000000061FE17
Address of Character 3: 000000000061FE16

我想打印整型变量integer_1[=25]space的所有四个字节的地址=],这意味着打印所有这四个 - 000000000061FE18000000000061FE19000000000061FE1A000000000061FE1B。我该怎么做?

您需要将 int 指针转换为 char 指针(或 int8_t 指针),然后遍历每个字节,如下所示:

char *cp = (char*)&integer_1;
for (int i = 0; i < sizeof(integer_1); ++i)
    printf("Address of integer_1, byte %d: %p\n",i,cp++);

这是你想要做的吗?

#include <stdio.h>

int main()
{
    int integer_1 = 12321;
    unsigned char* p = (unsigned char*)&integer_1;
    
    for (int i=0; i<sizeof(int); i++){
        printf("Address: %p -> Value: %02hhx\n", p+i, *(p+i));
    }
    return 0;
}

编辑:正如 KPCT 所指出的那样,使用 void* 确实是可能的,如果您也对所指向的值感兴趣,而不仅仅是地址,那么会更加乏味。

例如,将我的上述解决方案改编为使用 void*,将导致类似这样的结果

#include <stdio.h>

int main()
{
    int integer_1 = 12321;
    void* p = (void*)&integer_1;
    
    for (int i=0; i<sizeof(int); i++){
        printf("Address: %p -> Value: %02hhx\n", p+i, *((char*) p+i));
    }
    return 0;
}

无论如何你都必须通过转换为 char* 的地方