简体   繁体   English

我可以直接将任何整数值分配给指针变量吗?

[英]Can I assign any integer value to a pointer variable directly?

由于地址是数字并且可以分配给指针变量,我可以直接将任何整数值分配给指针变量,如下所示:

int *pPtr = 60000;

You can, but unless you're developing for an embedded device with known memory addresses with a compiler that explicitly allows it, attempting to dereference such a pointer will invoke undefined behavior. 您可以,但除非您正在为具有已知内存地址的嵌入式设备开发显式允许它的编译器,尝试取消引用此类指针将调用未定义的行为。

You should only assign the address of a variable or the result of a memory allocation function such as malloc , or NULL . 您应该只分配变量的地址或内存分配函数的结果,例如mallocNULL

Yes you can. 是的你可以。 You should only assign the address of a variable or the result of a memory allocation function such as malloc, or NULL. 您应该只分配变量的地址或内存分配函数的结果,例如malloc或NULL。

According to the pointer conversion rules, eg as described in this online c++ standard draft, any integer may be converted to a pointer value: 根据指针转换规则,如描述于例如网上的C ++标准草案,任何整数可以被转换为一个指针值:

6.3.2.3 Pointers 6.3.2.3指针

(5) An integer may be converted to any pointer type. (5)整数可以转换为任何指针类型。 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. 除非先前指定,否则结果是实现定义的,可能未正确对齐,可能不指向引用类型的实体,并且可能是陷阱表示。

Allowing the conversion does, however, not mean that you are allowed to dereference the pointer then. 但是,允许转换并不意味着您可以取消引用指针。

You can but there's a lot of considerations. 你可以,但有很多考虑因素。

1) What does that mean ? 1)这是什么意思

The only really useful abstraction when this actually gets used is that you need to access a specific memory location because something is mapped to a specific point, generally hardware control registers (less often: a specific area in flash or from the linker table). 实际使用时唯一真正有用的抽象是您需要访问特定的内存位置,因为某些内容映射到特定点,通常是硬件控制寄存器(较少:闪存中的特定区域或链接器表)。 The fact that you are assigning 60000 (a decimal number rather than a hexadecimal address or a symbolic mnemonic) makes me quite worried. 您分配60000(十进制数而不是十六进制地址或符号助记符)的事实让我非常担心。

2) Do you have "odd" pointers? 2)你有“奇怪的”指针吗?

Some microcontrollers have pointers with strange semantics (near vs far, tied to a specific memory page, etc.) You may have to do odd things to make the pointer make sense. 一些微控制器的指针具有奇怪的语义(靠近远处,与特定的存储页面绑定等)。您可能需要做一些奇怪的事情才能使指针有意义。 In addition, some pointers can do strange things depending upon where they point. 另外,根据指向的位置,一些指针可以做奇怪的事情。 For example, the PIC32 series can point to the exact same data but with different upper bits that will retrieve a cached copy or an uncached copy. 例如,PIC32系列可以指向完全相同的数据,但具有不同的高位,可以检索缓存副本或未缓存的副本。

3) Is that value the correct size for the pointer? 3)该值是指针的正确大小吗?

Different architectures need different sizes. 不同的架构需要不同的尺寸。 The newer data types like intptr_t are meant to paper over this. 像intptr_t这样的新数据类型就是为了解决这个问题。

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

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