【发布时间】:2012-08-25 08:32:26
【问题描述】:
我正在尝试在函数中分配内存,但我不确定我做错了什么。 我想要这个:
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;
}
}
但我收到此错误:Robust Simulation.exe 中 0x770d15de 处的未处理异常:0xC0000005:访问冲突读取位置 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。问题已解决。 -
这对教育目的很有好处,但在现实生活中你应该避免使用这样的代码。
标签: c++ arrays malloc main scoping