[英]Access violation, cant figure out the reason
因此,正在構建此類:
public class BitArray {
public:
unsigned char* Data;
UInt64 BitLen;
UInt64 ByteLen;
private:
void SetLen(UInt64 BitLen) {
this->BitLen = BitLen;
ByteLen = (BitLen + 7) / 8;
Data = new unsigned char(ByteLen + 1);
Data[ByteLen] = 0;
}
public:
BitArray(UInt64 BitLen) {
SetLen(BitLen);
}
BitArray(unsigned char* Data, UInt64 BitLen) {
SetLen(BitLen);
memcpy(this->Data, Data, ByteLen);
}
unsigned char GetByte(UInt64 BitStart) {
UInt64 ByteStart = BitStart / 8;
unsigned char BitsLow = (BitStart - ByteStart * 8);
unsigned char BitsHigh = 8 - BitsLow;
unsigned char high = (Data[ByteStart] & ((1 << BitsHigh) - 1)) << BitsLow;
unsigned char low = (Data[ByteStart + 1] >> BitsHigh) & ((1 << BitsLow) - 1);
return high | low;
}
BitArray* SubArray(UInt64 BitStart, UInt64 BitLen) {
BitArray* ret = new BitArray(BitLen);
UInt64 rc = 0;
for (UInt64 i = BitStart; i < BitLen; i += 8) {
ret->Data[rc] = GetByte(i);
rc++;
}
Data[rc - 1] ^= (1 << (BitLen - ret->ByteLen * 8)) - 1;
return ret;
}
};
剛寫完SubArray函數並繼續測試,但是在調用GetByte(i)的那一行上出現“訪問沖突:嘗試讀取受保護的內存”。 我測試了一下,它似乎與數據數組或i無關,將“ int derp = GetByte(0)”放在函數的第一行會產生相同的錯誤。
從類外部調用GetByte可以正常工作,我不知道發生了什么。
測試功能如下所示:
unsigned char test[] = { 0, 1, 2, 3, 4, 5, 6, 7 };
BitArray* juku = new BitArray(test, 64);
auto banana = juku->GetByte(7); //this works fine
auto pie = juku->SubArray(7, 8);
您可能要考慮創建一個字符數組 ,更改以下內容:
Data = new unsigned char(ByteLen + 1);
變成:
Data = new unsigned char[ByteLen + 1];
在前者中,括號內的值不是所需的長度,而是*Data
初始化為的值。 如果使用65(在ASCII系統中),則第一個字符變為A
話雖這么說,C ++已經擁有了一個非常高效的std::bitset
來確切地解決您所處的情況。如果您的目的是學習如何制作類,請務必編寫自己的類。 但是,如果您只是想簡化生活,則可能需要考慮使用已經提供的工具,而不是自己動手做。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.