简体   繁体   English

C中的指针铸造

[英]Casting of pointers in C

Can someone please explain me what these 2 lines mean?有人可以解释一下这两行是什么意思吗?

short * two_byte_pointer = (short*) 10;

int * four_byte_pointer = (int*) 10;

I thought that we can only use int* before the equal to sign.我认为我们只能在等号之前使用int* But how is it possible to cast a number with short* ?但是怎么可能用short*投射一个数字呢? I'm sorry if this is a dumb question.如果这是一个愚蠢的问题,我很抱歉。 I just started coding in C so I'm very confused.我刚开始在 C 编码,所以我很困惑。 Can you please explain me how pointers are also casted in C?你能解释一下如何在 C 中也投射指针吗?

Your code (for example first line) means:您的代码(例如第一行)意味着:

Dear compiler, here is a pointer to short short * .亲爱的编译器,这是一个指向 short short *的指针。
It is named two_byte_pointer .它被命名为two_byte_pointer
I would like it to have a value assigned = .我希望它有一个赋值=
The value I am thinking of is something else, but I want you to trust me that it is a pointer to short - honest (short*) .我正在考虑的价值是别的东西,但我希望你相信我,它是一个指向 short-Honest (short*)的指针。
The value I am using is 10.我使用的值是 10。

And I would not believe a word of it if I were your compiler or your colleague reading the code.如果我是您的编译器或阅读代码的同事,我一个字也不会相信。 Not without some explanatory comments and a quote from the memory part of the description of your environment.并非没有一些解释性注释和来自 memory 部分环境描述的引用。

It might make sense in some embedded environments with memory mapped special registers at an unusual location.在 memory 将特殊寄存器映射到不寻常位置的某些嵌入式环境中,这可能是有意义的。 Maybe not, see the comments by the busybee below.也许不是,请参阅下面的 busybee 的评论。
I am pretty sure that this is just a very theoretical example and "10" is just "a number example".我很确定这只是一个非常理论的例子,“10”只是“一个数字例子”。

The naming of the variables with two_byte and four_byte is based on assumptions on the sizes of types in your environment.使用two_bytefour_byte命名变量是基于对环境中类型大小的假设。 Apart from that I would name it pointer_to_two_byte , slightly longer, much more precise (not discussing naming style otherwise here).除此之外,我将其命名为pointer_to_two_byte ,稍长一些,更精确(此处不讨论命名风格)。

If you cast something the compiler just takes whatever value you provide and interprets it as the type you cast it to.如果您强制转换某些东西,编译器只会采用您提供的任何值并将其解释为您将其转换为的类型。 So in this example it will interpret 10 as a pointer to a short .所以在这个例子中,它将10解释为一个指向short的指针。 The value of a pointer is the memory address it points to.指针的值是它指向的 memory 地址。 Using this pointer will almost certainly fail because most systems don't allow you to access memory at such a low address.使用这个指针几乎肯定会失败,因为大多数系统不允许您在如此低的地址访问 memory。

Casting a number to a pointer can be useful if you need to do calculations on an address and use the result as a pointer.如果您需要对地址进行计算并将结果用作指针,则将数字转换为指针可能很有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM