简体   繁体   English

打印内存地址

[英]Printing Memory Address

I ran the following program on Cygwin on Windows8. 我在Windows8的Cygwin上运行了以下程序。

#include<iostream>
#include <stdio.h>
using namespace std;
int main(){
char c1 = 'a';
char c2 = 'b';
int i1 = 1;
float l1 = 100;
float f1 = 3.14;
double d1 = 1.424;
int i2;
char c3;
int i3;
printf("&c1 -> %u\n", (unsigned long)&c1);
printf("&c2 -> %u\n", (unsigned long)&c2);
printf("&i1 -> %u\n", (unsigned long)&i1);
printf("&l1 -> %u\n", (unsigned long)&l1);
printf("&f1 -> %u\n", (unsigned long)&f1);
printf("&d1 -> %u\n", (unsigned long)&d1);
printf("&i2 -> %u\n", (unsigned long)&i2);
printf("&c3 -> %u\n", (unsigned long)&c3);
printf("&i3 -> %u\n", (unsigned long)&i3);
}

My laptop gave the results below. 我的笔记本电脑给出了以下结果。

$ ./a.exe
&c1 -> 2337487
&c2 -> 2337486
&i1 -> 2337480
&l1 -> 2337476
&f1 -> 2337472
&d1 -> 2337464
&i2 -> 2337460
&c3 -> 2337459
&i3 -> 2337452

I understand that each data type has its own size and takes up memory addresses according to the size. 我知道每种数据类型都有自己的大小,并根据大小占用内存地址。 For example, in this case, since char type has only 1 byte size, the variable c1 takes up 1 memory address(2337487), and the next variable c2 starts from the address 2337486. However, I was confused by that i1 starts from 2337480. If c2 is also a char type variable, shouldn't it take up only one address? 例如,在这种情况下,由于char类型只有1个字节大小,因此变量c1占用1个内存地址(2337487),而下一个变量c2从地址2337486开始。但是,我对i1从2337480开始感到困惑。如果c2也是一个char类型的变量,它不应该只占用一个地址吗? And i1 start from 2337485? i1从2337485开始?

I guess it's something to do with a compiler, but don't understand how it works.Would anyone give me some advice? 我想这与编译器有关,但不了解它是如何工作的,有人会给我一些建议吗?

This is because of data structure alignment. 这是因为数据结构对齐。

For example, when the computer's word size is 4 bytes (a byte means 8 bits on most machines, but could be different on some systems), the data to be read should be at a memory offset which is some multiple of 4. When this is not the case, eg the data starts at the 14th byte instead of the 16th byte, then the computer has to read two 4 byte chunks and do some calculation before the requested data has been read, or it may generate an alignment fault. 例如,当计算机的字长为4个字节(一个字节在大多数机器上表示8位,但在某些系统上可能有所不同)时,要读取的数据应处于4的倍数的内存偏移量。情况并非如此,例如,数据从第14个字节而不是第16个字节开始,则计算机必须读取两个4字节的块,然后在读取请求的数据之前进行一些计算,否则可能会产生对齐错误。 Even though the previous data structure ends at the 13th byte, the next data structure should start at the 16th byte. 即使前一个数据结构在第13个字节处结束,下一个数据结构也应在第16个字节处开始。 Two padding bytes are inserted between the two data structures to align the next data structure to the 16th byte. 将两个填充字节插入两个数据结构之间,以使下一个数据结构与第16个字节对齐。

这是编译器的最佳化:有时,如果分配的内存不是固定块,则更快。

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

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