内存是如何分配给不同数据类型的变量的? [英] How is Memory Allocated to variables of different data types?

查看:29
本文介绍了内存是如何分配给不同数据类型的变量的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了以下代码.

#include<stdio.h>

int main()
{
    int x = 1 ;
    int *j = &x ;
    int y =  2 ;
    int *t = &y ;

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

输出为 0028FF14 0028FF10.

我想说的一点是地址之间的差异是4".

The Point I want to make is that the difference between the addresses is `4'.

而在这种情况下

#include<stdio.h>

int main()
{
    char x = 't' ;
    char *j = &x ;
    char y =  'f' ;
    char *t = &y ;
    printf("%p
" , (void *)j);
    printf("%p" , (void *)t);    

   }   

输出为0028FF17 0028FF16

区别在于1.

第一种情况的区别是 4.而在第二种情况下,它是 1.为什么会这样?

Difference In First Case is 4. Whereas in the second case it is 1. Why is it so?

如果我单独打印所有内存地址的值,我会得到什么?

And What will I get if I printed value at all memory addresses individually?

也许真的很一般,大家都知道,但我刚开始学C,所以程序的输出让我很困惑.

Maybe It is really general and known, but I just started C, So the output of the program confuses me.

更新
现在使用 %p 格式并将指针值转换为 void* 以按照 Keith Thompson 的建议打印指针值.

Update
Now Using %p format and converted the pointer value to void* to print the pointer value as suggested by Keith Thompson.

推荐答案

对声明的对象在内存中的排列顺序没有要求.显然,您使用的编译器恰好将 xy 放在一起.它可以在它们之间放置了 j,但它没有.

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.

另外,打印指针值的正确方法是使用%p格式,将指针值转换为void*:

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

printf("%p
", (void*)j);
printf("%p
", (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.

这篇关于内存是如何分配给不同数据类型的变量的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆