简体   繁体   English

为什么int和char的地址相差16?

[英]Why is the difference between the addresses of int and a char is 16?

I declared an integer (32bits) and a char (8), and I know that a computer address is 1 byte at a time, so why is the difference between those two addresses is 16 and not let's say 40?我声明了一个整数(32 位)和一个字符(8),并且我知道计算机地址一次是 1 个字节,那么为什么这两个地址之间的差异是 16 而不是 40? if each memory address is 8 bits and the size of an integer is 32, then the range is expected to be greater than 16, no?如果每个内存地址是 8 位,整数的大小是 32,那么范围应该大于 16,不是吗?

int main(void)
{
    char a = 'g';
    int b = 5;
    printf("%p %p\n", &a, &b);

    return 0;
}
(gdb) p 0x7fffadfcc2c0 (a) - 0x7fffadfcc2b0 (b)
$1 = 16

The difference between memory addresses is in bytes, not bits.内存地址之间的差异以字节为单位,而不是位。

The minimum difference between the addresses of these two variables is 1, if the address of a is less than the address of b, because the size of a is 1 byte.如果 a 的地址小于 b 的地址,这两个变量的地址之间的最小差异是 1,因为 a 的大小是 1 字节。

The minimum difference is 4, if the address of b is less than the address of a, because the size of b is 4 bytes.如果 b 的地址小于 a 的地址,最小差是 4,因为 b 的大小是 4 个字节。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM