已分配但未初始化

allocated but not initialized

本文关键字:初始化 分配      更新时间:2023-10-16

我遇到了一个已分配但未初始化的问题。

下面是部分代码:

void test2(vector<string> names, int num) // just for test
{
    const char  **tmp = new const char *[num]; // issue happends here.
    for(int i = 0; i < num; i ++)
        tmp[i] = names[i].c_str(); // is it not inialization???
    //call another function using tmp
    delete []tmp; 
}

在代码的第3行,我遇到了一个问题:赋值:"tmp" = "新char const *[num]",这是分配的,但没有初始化。

我相信我对二维数组的分配和初始化感到困惑。我认为tmp是const char *数组,我只是想把向量转换成const char **;

那么在代码中,这里使用new和delete是否正确?

我知道,如果2d数组是int*,那么如果我想给它赋值,我需要新的int[num],然后做一个for循环到新的int[];但是我的案子呢?

有人能帮我弄一下这段代码吗?

在这种情况下不要使用const,因为您是在初始化后分配数据。