gpt4 book ai didi

c++ - 在函数中初始化,不在main中初始化

转载 作者:搜寻专家 更新时间:2023-10-31 00:42:17 25 4
gpt4 key购买 nike

我正在尝试在函数中分配内存,但我不确定自己做错了什么。我想要这个:

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;
}

是否存在范围界定问题?我想既然我给它传递了一个指针,它就会被分配,我将能够在初始化函数之外访问它。

谢谢你的帮助

最佳答案

进行以下更改:-

initialize(&test, 10);
....


void initialize(int** test, int count)
{
*test = new int[count];
for (int i = 0; i < count; i++)
{ (*test)[i] = i; }
}

C++ 有另一个称为引用的特性,如果你愿意的话:-

void initialize(int*& test, int count)
{
test = new int[count];
for (int i = 0; i < count; i++)
{ test[i] = i; }
}

你正在做的是通过测试 [from main](地址将通过)并存储在另一个名为 test 的局部指针变量中。这个新变量具有函数作用域的生命周期,并且将在函数完成后很快被删除留下垃圾.

另一种选择是

int* test= initialize(test, 10);

并更改初始化为

int* initialize(int* test, int count)
{
test = new int[count];
for (int i = 0; i < count; i++)
{ test[i] = i; }
return test;
}

关于c++ - 在函数中初始化,不在main中初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12199831/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com