我想在函數中分配內存,我不知道我在做什麼錯。 我想這一點:在函數中初始化,並沒有在主要初始化
int main()
{
int* test= 0;
initialize(test, 10);
int test2 = test[2];
delete[] test;
}
void initialize(int* test, int count)
{
test = new int[count];
for (int i = 0; i < count; i++)
{
test[i] = i;
}
}
但我收到此錯誤:未處理的異常在0x770d15de魯棒Simulation.exe:0000005:訪問衝突讀取位置0x00000008。 斷行:int test2 = test [2];
但這個工程:
int main()
{
int* test=0;
test = new int[10];
for (int i = 0; i < 10; i++)
{
test[i] = i;
}
int test2 = test[2];
delete[] test;
}
有一個範圍的問題嗎?我想,因爲我傳遞了它將被分配的指針,我可以在初始化函數之外訪問它。
感謝您的幫助
降'new'和'delete',使用'VECTOR'。問題已修復。 –
這對教育目的很有好處,但在真實情況下你應該避免這樣的代碼。 – juanchopanza