【问题标题】:Initialized in a function and is not initialized in main在函数中初始化,而不是在 main 中初始化
【发布时间】: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;
}

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

感谢您的帮助

【问题讨论】:

  • 删除newdelete,使用vector。问题已解决。
  • 这对教育目的很有好处,但在现实生活中你应该避免使用这样的代码。

标签: c++ arrays malloc main scoping


【解决方案1】:

进行以下更改:-

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

你正在做的是通过测试[来自 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;
    }

【讨论】:

    【解决方案2】:

    指针也是按值传递的。你需要:

    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 中的原始指针从未被初始化。

    【讨论】:

    • test 仍然为0 时,更不用说test[2]。这就是为什么它在读取0x00000008 时出现问题,这是OP 的两个超过0 的int 宽度。
    【解决方案3】:

    您需要将对指针的引用传递给您的initialise 函数。将原型更改为

    void initialize(int* &test, int count) 
    

    new 的返回值被分配给按值传递时创建的指针的副本。因此,当函数退出时,该地址会随着副本超出范围而丢失,因此您会发生内存泄漏。因此,您的 test 指针实际上从未指向任何已分配的内存,因此删除它会给您带来访问冲突。

    通过引用传递允许函数修改test指针

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-23
      • 2011-05-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多