this is snippet of Block class :
class Block { public:
//size satu blok(dalam byte)
static const int BLOCK_SIZE = 4096;
Block(int number,byte *data):number(number) {
for(int i=0;i<BLOCK_SIZE;i++) {
this->data[i] = data[i];
}
}
void test();
private:
byte data[BLOCK_SIZE];
const int number; };
note that byte is just typedef unsigned char
and this is one of the function in other class that initialize block variable
bool Filesystem::getBlock(int number, Block *block) {
fstream fin(path);
if(!fin.is_open() || number<0) {
return false;
}
byte data[Block::BLOCK_SIZE];
fin.seekg(Block::BLOCK_SIZE*number,ios::beg);
for(int i=0;i<Block::BLOCK_SIZE;i++) {
fin>>data[i];
}
block = new Block(number,data);
(*block).test();//this is the first test, this prints values as expected
fin.close();
return true;
}
this is another snippet :
Block *superblock;
getBlock(0,superblock);
(*superblock).test();//this is the second test, this prints random value
test is a function that prints the first four bytes from data in block
when i first use the test function inside the getblock, it prints exactly like i wanted(same as the file) but when i tried to print it the second time exactly after i call getblock, it prints random value
anyone knows where the mistake?
This line creates a new
Blockobject and assigns it to the parameterblock. However, the pointerblockis passed into the function by value, so the original pointersuperblockis not affected by this line. Hence, you are operating on differentBlock-objects inside and outside of your function.To solve this problem, you can use a reference to a pointer as your parameter: