我明白,這條語句是將一個無符號的易失性字符轉換爲內存地址,但我不明白的是volatile之後的指針。我不明白爲什麼在劇組中使用指針
#define PORTC *(unsigned char volatile *)(0x1003)
我明白,這條語句是將一個無符號的易失性字符轉換爲內存地址,但我不明白的是volatile之後的指針。我不明白爲什麼在劇組中使用指針
#define PORTC *(unsigned char volatile *)(0x1003)
它說:將數字0x1003
視爲一個易失性的無符號字符指針;讀取或寫入該地址處的(字節)值,具體取決於它如何使用:
unsigned char c = PORTC; // read
PORTC = c + 1; // write
這並非如此。相反,它將值0x1003解釋爲一個指針,然後它是取消引用該指針獲取類型爲volatile unsigned char
的值。實質上,這是一種在固定內存位置訪問字節的方法。 (其中「volatile
」強制一個實際的「訪問」,以該存儲位置,這是在標準稍微定義模糊的概念。)
(TYPE*) POINTER
是這被解釋爲指針的類型鑄語法。 例如,
int m = 4;
char* p_char = (char*)&m;
因此,p_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
你看這個地方上的I/O端口映射到特定的內存地址的處理器,所以當你讀或寫'PORTC'您正在與外部設備交換信息。 –