我正在嘗試從二進制檔案中讀取,然后將二進制資訊從char[]指標轉換為int[]指標。
我想知道,是否有類似的東西static int var[],但對于動態分配的陣列?
我試圖找到一種方法來告訴 C 在退出函式后不要釋放記憶體。
imagein.open(loc, ios::binary);
//Creates a pointer to a list of chars with a length of 8, which is just enough for 2 ints
char* timechar = new char[8];
//Reads 8 bytes of data from the file
imagein.read(timechar, 8);
//Creates an int pointer with enough room for 2 vars
int* ints = new int[2];
//Tells C that everything within timechar is now an int, and copies the contents to the ints pointer
ints = (int*)timechar;
//gets the width, and height of the image from the 1st 2 bytes
width = ints[0];
height = ints[1];
//Creates the size var
size = width * height;
//sets the ammout of ints to read to the width * height
times = size;
//creates a pointer to a list of chars so that we can read the data from the file
char* chars = new char[times * 4];
//Reads the rest of the file into chars
imagein.read(chars,times*4);
//reinitilizes buffer to be the correct size to the compiler
int* temp= new int[size 2];
//shifts the pointer to the buffer over twice
temp;
temp;
//takes everything from chars and tells C that all the bits within the chars var are copied over as int's
temp = (int*)chars;
//Shifts the buffer pointer back to where it should be
--temp;
--temp;
//sets the 1st, and 2nd buffer vars to the width, and height of the given image
temp[0] = width;
temp[1] = height;
//increases size to the correct size of the array buffer
size = 2;
我想讓temp[]int 在退出函式后持續存在。
我是 C 新手,我不確定其他方法可以完成我想做的事情。
uj5u.com熱心網友回復:
編輯:這很可能不是 OP 需要的,但這是他們要求的,所以我會保留這個答案而不是洗掉它,以防其他人登陸這里。
我試圖找到一種方法來告訴 C 在退出函式后不要釋放記憶體。
人們想要這樣做的正常原因是在函式的多次呼叫中回收動態分配的記憶體。它“有時”具有有趣的性能優勢,但代價是阻止該函式同時在多個執行緒中使用。
如果這不是您想要做的,請停止閱讀。除此以外...
如果您想以這種方式回收臨時動態存盤,那么靜態區域變數將為您提供所需的內容。
這是使用 a 的樣子std::vector<>,你真的應該用它來代替原始陣列指標。
void someFunction(std::size_t size) {
static vector<int> temp;
// ...
if(temp.size() < size 2) {
temp.resize(size 2);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/462801.html
