如何存储在内存中的指针? [英] How are pointers stored in memory?

查看:236
本文介绍了如何存储在内存中的指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有点糊涂了这一点。
在我的系统,如果我这样做:

 的printf(%D的sizeof(INT *));

这将只产生4。现在,同样的情况发生在的sizeof(INT)。结论:如果两个整数和指针是4个字节,指针可以安全地转换为一个int
 (即,存储器它指向可以存储在一个int)。但是,如果我这样做:

 为int * X;
的printf(%P,X);

返回的十六进制地址是远远超出了INT范围,因此任何试图存储在一个int值明显失败。

这怎么可能?如果指针需要4个字节的内存,它怎么可以存储超过2 32

编辑:
正如一些网友建议,我张贴了code和输出:

 的#include<&stdio.h中GT;诠释的main()
{
    的printf(%d个\\ N的sizeof(INT));
    的printf(%d个\\ N的sizeof(INT *));    INT * X;
    的printf(%d个\\ N的sizeof(X));
    的printf(%P \\ N,X);
}

输出:

  4
4
4
0xb7778000


解决方案

C11,6.3.2.3,第5和6:


  

的整数可以被转换为任何指针类型。除previously规定,
  结果是实现定义的,可能无法正确​​对齐,可能不会指向一个
  所引用类型的实体,可能会重新presentation一个陷阱。


  
  

不限指针类型可被转换成一个整数类型。除previously规定,
  结果是实现定义的。如果结果不能重新在整型psented $ P $,
  该行为是不确定的。结果不必是任何整数的值的范围
  类型。


因此​​转换是允许的,但结果是实现定义(或未定义如果结果不能被存储在整数型)。 (其中pviously指定$ P $指的是NULL。)

在问候你的打印语句为指针打印的东西比4个字节的数据可以重新present大,这是不正确的,因为 0xb7778000 距离范围内32位整数类型。

I'm a little confused about this. On my system, if I do this:

printf("%d", sizeof(int*));

this will just yield 4. Now, the same happens for sizeof(int). Conclusion: if both integers and pointers are 4 bytes, a pointer can be safely "converted" to an int (i.e. the memory it points to could be stored in an int). However, if I do this:

int* x;
printf("%p", x);

The returned hex address is far beyond the int scope, and thus any attempt to store the value in an int fails obviously.

How is this possible? If the pointer takes 4 bytes of memory, how can it store more than 232?

EDIT: As suggested by a few users, I'm posting the code and the output:

#include <stdio.h>

int main()
{
    printf ("%d\n", sizeof(int));
    printf ("%d\n", sizeof(int*));

    int *x;
    printf ("%d\n", sizeof(x));
    printf ("%p\n", x);
}

The output:

4
4
4
0xb7778000

解决方案

C11, 6.3.2.3, paragraphs 5 and 6:

An integer may be converted to any pointer type. Except as previously specified, the result is implementation-defined, might not be correctly aligned, might not point to an entity of the referenced type, and might be a trap representation.

Any pointer type may be converted to an integer type. Except as previously specified, the result is implementation-defined. If the result cannot be represented in the integer type, the behavior is undefined. The result need not be in the range of values of any integer type.

So the conversions are allowed, but the result is implementation defined (or undefined if the result cannot be stored in an integer type). (The "previously specified" is referring to NULL.)

In regards to your print statement for a pointer printing something larger than what 4 bytes of data can represent, this is not true, as 0xb7778000 is within range of a 32 bit integral type.

这篇关于如何存储在内存中的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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