将指针强制转换为int和back [英] Casting a pointer to an int and back

查看:170
本文介绍了将指针强制转换为int和back的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以通过指向int和back的指针进行定义?

喜欢:


typedef struct

{

int无论如何;

} S;


int main(无效)

{

S * s = malloc(sizeof(S));

int i =(int)s;

S * t = (S *)i;

t.whatever = 42;



}


/ David

Is it well-defined to make a cast from a pointer to an int and back?
Like:

typedef struct
{
int whatever;
} S;

int main(void)
{
S* s = malloc(sizeof(S));
int i = (int) s;
S* t = (S*) i;
t.whatever = 42;
etc.
}

/David

推荐答案


pi ************ @ gmail.com 写道:
是否定义良好从指向int和back的指针?


不,不是。


你可能很幸运,它适用于你的实施,但不算数
就可以了(即它不便携)。


一些问题:


- 指针如何映射到整数?

- 整数如何映射到指针(不一定与上面相同)?

- 是一个足以容纳地址值的整数(即使上面是

罚款)?


即使以上所有内容都适用于一个实现/架构,

也可能不在其他实现/架构上。


就是不要这样做。另外,看看你遇到的其他问题,

以下:

喜欢:


#include< stdlib。 h>


否则`malloc`是未知的。

typedef struct
{
int whatever;
} S;

int main(void)
{* S * s = malloc(sizeof(S));
int i =(int)s;
S * t =(S *)i;
t.whatever = 42;


你的意思是:


t->无论= 42;





(* t).whatever = 42;




这是语法错误。 />

请发布完整的,可编译的,最小的例子。

}
Is it well-defined to make a cast from a pointer to an int and back?
No, it is not.

You may be lucky that it works on your implementation, but don''t count
on it (i.e. it''s not portable).

Some concerns:

- how do pointers map to integers?
- how do integers map to pointers (not necessarily same as above)?
- is an integer wide enough to hold an address value (even if above is
fine)?

Even if all of the above are fine for one implementation/architecture,
the may not be on others.

Just don''t do it. Also, have a look at other things you got wrong,
below:
Like:
#include <stdlib.h>

Otherwise `malloc` is unknown.
typedef struct
{
int whatever;
} S;

int main(void)
{
S* s = malloc(sizeof(S));
int i = (int) s;
S* t = (S*) i;
t.whatever = 42;
You certainly mean:

t->whatever = 42;

or

(*t).whatever = 42;
etc.
This is a syntax error.

Please post full, compileable, minimal examples.
}



-

BR,Vladimir


--
BR, Vladimir


2006-02-22,Vladimir S. Oka< no **** @ btopenworld.com>写道:
On 2006-02-22, Vladimir S. Oka <no****@btopenworld.com> wrote:
etc。



这是语法错误。



This is a syntax error.




很好看。转到学生班的顶部。



Well spotted. Go to top of the pedants class.


pi ************ @ gmail.com 写道:
是否可以通过指向 int和back?
Is it well-defined to make a cast from a pointer to an
int and back?




我不这么认为。


例如,在某些平台上,

sizeof(int)= 4和sizeof(void *)= 8



I don''t think so.

For example, on some platforms,
sizeof(int) = 4 and sizeof(void *) = 8


这篇关于将指针强制转换为int和back的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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