已在函数中初始化,但未在main中初始化

Initialized in a function and is not initialized in main

本文关键字:初始化 main 函数      更新时间:2023-10-16

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

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指针