我有此代码:
#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;
}
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
答案 0 :(得分:3)
C增量指针不是按字节而是按类型的大小指向。 也就是说,如果您有指向int的指针,则它会按sizeof(int)递增-在您的示例中为4。
答案 1 :(得分: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;
}
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