打印某个变量的整个地址块[关闭]

问题描述 投票:0回答:2

我有这个代码:

#include <stdio.h>

int main(void) {
    int a = 56;
    printf("First part of address block:\n");
    printf("%p", &a);
    printf("All parts of address block:\n");
    printf("%p\n%p\n%p\n%p", &a, &a + 1, &a + 2, &a + 3);
    return 0;
}

Output:

First part of address block:                                                        
0x7fffd029ecec                                                                               
All parts of address block:                                                                             
0x7fffd029ecec                                                                               
0x7fffd029ecf0                                                                               
0x7fffd029ecf4                                                                               
0x7fffd029ecf8  

在我看来,int的地址块看起来像这样:

| 0x7fffd029ece**c** | 0x7fffd029ece**d** | 0x7fffd029ece**e** | 0x7fffd029ece**f** |
|      0000          |      0000          |      0011          |      1000    
c pointers hex memory-address
2个回答
3
投票

C指针增量指针不是按字节,而是指向类型的大小。也就是说,如果你有指向int的指针,它会增加sizeof(int) - 在你的例子中是4。


0
投票

正如Alex所说,指针数学按类型的大小递增,而不是字节。

您可以通过将&a强制转换为char*(也就是字节指针)来满足您的期望:

int main(void) {
    int a = 56;
    printf("First part of address block:\n");
    printf("%p", &a);
    printf("All parts of address block:\n");
    printf("%p\n%p\n%p\n%p", &a, ((char*)&a) + 1, ((char*)&a) + 2, ((char*)&a) + 3);
    return 0;
}

以下是我编写它以使其处理平台大小的方法:

#include <stdio.h>

int main(void) {
    int a = 56;
    char* p = (char*)&a;
    printf("First part of address block:\n");
    printf("%p\n", &a);
    printf("All parts of address block:\n");
    for(int i=0;i<sizeof(a); ++i) printf("%p : [%d] : 0x%02x\n", p+i, i, *(p+i));
    return 0;
}

Output

Success #stdin #stdout 0s 9424KB
First part of address block:
0x7ffff2e39c5c
All parts of address block:
0x7ffff2e39c5c : [0] : 0x38
0x7ffff2e39c5d : [1] : 0x00
0x7ffff2e39c5e : [2] : 0x00
0x7ffff2e39c5f : [3] : 0x00
© www.soinside.com 2019 - 2024. All rights reserved.