我有這樣的代碼和IM停留在第二行這段代碼做了什麼? (關於指針)
unsigned long check_password(const char* p){
int* ip = (int*)p;
int i;
int res=0;
for(i=0; i<5; i++){
res += ip[i];
}
return res;
}
int* ip = (int*)p;
是什麼意思行?
我有這樣的代碼和IM停留在第二行這段代碼做了什麼? (關於指針)
unsigned long check_password(const char* p){
int* ip = (int*)p;
int i;
int res=0;
for(i=0; i<5; i++){
res += ip[i];
}
return res;
}
int* ip = (int*)p;
是什麼意思行?
unsigned long check_password(const char* p){
int* ip = (int*)p; // line 2, non-const not required
int i;
int res=0;
for(i=0; i<5; i++){
res += ip[i]; // line 6
}
return res;
}
第2行聲明ip
作爲指針整數和其初始化爲(int*)p
。 (int*)p
是一個C風格演員,在這種情況下,解析爲reinterpret_cast<int*>(const_cast<char*>(p))
。見
When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used?
ip
現在指向p的存儲位置。當使用ip
時,該位置的內存被解釋爲保持一個整數,即使它擁有一個char;並且它可以被修改,即使它最初被聲明爲const。
線6對待ip
,如果它是指向的int
陣列的第一個元素,並增加了該數組res
的i
個元素。很可能ip
實際上指向char
數組的第一個元素。這意味着,該陣列的每個迭代sizeof(int)
連續元素被解釋爲單個int
的表示。
該代碼的意圖是可能,即5 int
秒的序列被作爲長sizeof(int)*5
的char
陣列通過。
請注意,如果p
實際上並未指向至少爲sizeof(int)*5
的內存,則該代碼爲UB,因爲該區域中的內存已被讀取。即數組必須至少長度爲sizeof(int)*5
。
虛擲在你的代碼中的常量不需要
unsigned long check_password(const char* p){
const int* ip = reinterpret_cast<const int*>(p);
int res = 0;
for (int i = 0; i < 5; ++i){
res += ip[i];
}
return res;
}
int * ip =(int *)p;這條線是什麼意思?
這意味着,「創建一個指向與p相同的地址開始的整數的指針」。
函數期望p指向一個代表5個整數的字節序列。
此功能的行爲如果p確實是指向整數序列被轉換爲const char*
在練習之前只定義了,這段代碼的作者是假設:
字節序列已經以這樣的方式編碼,即它們真正代表了本機上的5個整數(考慮到體系結構的字大小和字節順序)。
由p表示的地址的對齊對於將內存定位爲整數是正確的(一些處理器在這方面有限制)。
這可能不是您想要複製或學習的代碼,而不是作爲警示故事。
[這](http://stackoverflow.com/q/388242/1870232)可能會有所幫助。 – P0W
它看起來非常糟糕。 – NathanOliver
該代碼定義了從指向'char'的指針指向'int'類型的新指針。 –