我明白这个语句是将一个unsigned volatile char转换为内存地址,但我不明白的是volatile之后的指针。
#define PORTC *(unsigned char volatile *)(0x1003)
答案 0 :(得分:5)
它说:将数字0x1003
视为易失性无符号字符指针;读取或写入该地址的(字节)值,具体取决于它的使用方式:
unsigned char c = PORTC; // read
PORTC = c + 1; // write
答案 1 :(得分:5)
这不是正在发生的事情。相反,它将值0x1003解释为指针,然后它解除引用该指针获取类型volatile unsigned char
的值。实质上,这是一种在固定内存位置访问字节的方法。 (“volatile
”强制对该内存位置实际“访问”,这在标准中是一个有点模糊定义的概念。)
答案 2 :(得分:0)
(TYPE*) POINTER
是一种语法,被解释为指针的类型转换。 例如,
int m = 4;
char* p_char = (char*)&m;
因此,p_char
是指向char的指针。如果我们取消引用p_char
,即*p_char
,则p_char
指向的位置处的二进制表示将转换为char
(字符)的表示。该值的确切结果是未定义的。我不知道它将返回什么样的确切值,但它会返回类似奇怪字符č
的东西。
为了更深入地理解指针,我想强调一个指针只是访问以C ++语言表示并驻留在计算机内存中的实体的接口之一。
#include <iostream>
using namespace std;
/*
* C++ interface to represent entity which resides on computer memory:
* ---------
* 1) object;
* 2) pointer;
* 3) reference;
*
* C++ interpretation of entity through interface: TYPE
* -------------- ----
*
* What is the function of TYPE?
* 1) tell compiler the size of an object of this TYPE needed; ( sizeof( int ) -> 4 bytes )
* 2) when the value of object at which it resides is dereferenced,
* the binary represented value is transformed to some other
* representation value according to the TYPE's interpretation rule; ( if int, interpret it as an int )
*
*
* +----------------+
* | 0x02105207 |
* | 0x02105206 |
* | 0x02105205 |
* int n | 0x02105204 |
* +----------------+
* | 0x02105203 |
* | 0x02105202 |
* | 0x02105201 |
* ---->int m | 0x02105200 |
* | +----------------+
* | | |
* | +----------------+
* | ... ...
* | +----------------+
* ---- int* p | 0x00002298 |
* +----------------+
*
* if the pointer in figure is declared as:
*
* int* p = &m;
*
* the face of 0x00002298 -> 0x02105200 will not be changed until p is
* assigned to other address value;
*
*
*/
class consecutive_two_int
{
public:
consecutive_two_int():m(4),n(123){}
int m;
int n;
};
int main()
{
int * p;
consecutive_two_int obj;
p = &(obj.m);
for( int i = 0; i < 8; ++i )
{
// because pointer of char progresses every 1 byte;
// increment memory byte by byte through it;
cout << *(int*)( (char*)p + i ) << "\n";
}
return 0;
}
作为一个例子,结果是:
4 // the first defined int
2063597568 // undefined
8060928 // undefined
31488 // undefined
123 // the second defined int
268435456 // undefined
1175453696 // undefined
-465170432 // undefined