【问题标题】:allocated but not initialized已分配但未初始化
【发布时间】:2013-05-13 19:04:58
【问题描述】:

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

这里是部分代码:

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 行,我遇到了一个问题:Assigning: "tmp" = "new char const *[num]",它已分配但未初始化。

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

那么在代码中,这里使用new和delete对吗?

我知道如果二维数组是int*,那么如果我想给它赋值,我需要new int[num],然后对new int[]做一个for循环;但是我的情况呢?

有人可以帮我处理这段代码吗?

【问题讨论】:

  • 常数是常数。
  • 您遇到了什么问题?编译器在抱怨吗?如果是这样,请发布消息。代码没有按照您的预期执行吗?展示你是如何练习代码的,描述你期望它做什么,以及它实际上在做什么。
  • 我怀疑问题中的代码与您遇到问题的代码并不完全相同。
  • 什么程序给了你这个信息? I can't reproduce it easily
  • @IsmetAlkan - 你的意思是什么?

标签: c++ allocation


【解决方案1】:

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

【讨论】:

  • 我觉得我最好用vector;
  • const char tmp = new const char *[num];这里只是分配,只要分配内存就必须初始化。而在for循环中,不是初始化,而是赋值。所以在这种情况下,我们最好使用 vector 而不是 const char
猜你喜欢
  • 2011-12-28
  • 1970-01-01
  • 2019-01-28
  • 1970-01-01
  • 1970-01-01
  • 2020-12-25
  • 1970-01-01
  • 2019-06-18
  • 1970-01-01
相关资源
最近更新 更多