已在函数中初始化,但未在main中初始化
Initialized in a function and is not initialized in main
我试图在函数中分配内存,但我不确定我做错了什么。我想要这个:
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;
}
指针也通过值传递。您需要:
void initialize(int*& test, int count)
您的版本不会更改原始指针:
void initialize(int* test, int count)
{
//test is a copy of the pointer because it was passed by value
//...
}
在这之后,delete[]
失败的原因就显而易见了——因为main
中的原始指针从未初始化。
您需要将对指针的引用传递到initialise
函数中。将原型更改为
void initialize(int* &test, int count)
new
的返回值分配给传递值时创建的指针的副本。因此,当函数退出时,由于副本超出范围,该地址将丢失,因此内存泄漏。因此,test
指针实际上从未指向任何分配的内存,因此删除它会导致访问冲突。
通过引用传递允许函数修改test
指针
相关文章:
- 在main()之外初始化std::vector会导致性能下降(多线程)
- 为什么 'main' 函数中的局部 int 变量会自动初始化?
- 使用函数从 Visual Studio 2017 中的 main 创建和初始化数组
- C++ main 函数中初始化静态变量
- 如何使用GDB跟踪Main()之前初始化的所有静态全局变量
- 如何在 main 函数的一个对象中初始化两个类的值?C++
- 实用程序函数不会在 .h 文件中初始化并在 main 中定义.cpp
- 静态变量需要在MAIN处理ARGV参数之前进行初始化
- 静态内联变量是否需要在 main 之前初始化?
- 如何在另一个函数中初始化在 main 中声明的数组
- 非本地非内联变量的初始化:是否严格在"main()"函数调用之前进行
- 可以(通过编译器)使用多少个线程来初始化全局对象(函数main之前)
- Main()函数中的默认初始化
- C++ 如何从 main() 外部访问在 main() 中初始化的对象
- C++ - 在一个函数/文件中初始化变量然后在main()/另一个文件中使用它的最佳方法是什么?
- 已在函数中初始化,但未在main中初始化
- C++当我们创建对象时,构造函数会初始化,但是如果我想再次重新初始化对象,请在 main 的某个时候说该怎么做
- 通过派生类构造函数初始化后,从main()访问基类变量
- C++编译器在 main 之后实现动态初始化
- 在 main() 消失之前初始化的值