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

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

问题描述

我编写了以下代码.

#include<stdio.h>

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

    printf("%p\n" , (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\n" , (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.

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

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\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.

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

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