How is Memory Allocated to variables of different data types?

六眼飞鱼酱① 提交于 2019-11-29 13:06:10

There are no requirements on the order in which declared objects are laid out in memory. Apparently the compiler you're using happens to place x and y next to each other. It could have placed j between them, but it didn't.

Also, the correct way to print a pointer value is to use the %p format and convert the pointer value to void*:

printf("%p\n", (void*)j);
printf("%p\n", (void*)t);

This produces an implementation-defined human-readable representation of the pointer value, typically but not always in hexadecimal.

If you care about the order in which declared variables are allocated in memory, you're probably doing something wrong, or at least not useful. Let the compiler worry about where to put things. It knows what it's doing.

Well for starters the difference isn't always four, it just happens to be four by happy coincidence. The compiler is allowed to stick variables in memory where ever it wants to. In this case it has put your two variables next to each other in memory and the difference can be explained as that is how big an integer is on your system(4 bytes) and how big a character is on your system(1 byte). On other systems they may be different sizes and placed in different locations.

Each integer takes up four bytes, therefore, each integer memory address is offset by 4. A char only takes up one byte, therefore its memory addresses are offset by one.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!