我想在函数中分配内存,我不知道我在做什么错。 我想这一点:在函数中初始化,并没有在主要初始化
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