【问题标题】:Create 2D array with "new"? [duplicate]用“新”创建二维数组? [复制]
【发布时间】:2012-01-12 10:14:36
【问题描述】:

我想创建一个如下所示的二维数组。

char **dog = new char[480][640];

但它出错了:

error C2440: 'initializing' : cannot convert from 'char (*)[640]' to 'char ** '
        Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast

使用“新”我需要做什么? (不使用 calloc、malloc 或 char dog[480][640];

【问题讨论】:

  • char (*p)[640] = new char[480][640]; 请注意,T 的二维数组与指向T 数组的指针数组不同。哦,宁可使用std::vector 而不是原始new。干杯&hth.,
  • 是的,std::vector<std::array<char, 640> > dog(480);
  • @Mooing Duck:它涵盖了 640x350 和 640x480 的分辨率,但这样混合 vectorarray 确实有点奇怪。我想我会一直使用vector,忘记使用array 可能进行的微优化,并作为额外的奖励获取适用于更多当前编译器的代码。干杯,

标签: c++


【解决方案1】:

类似这样的:

char **dog = new char *[480];
for (int i = 0; i < 480; i++)
    dog[i] = new char[640];

和删除的时候一样,但是先循环。

【讨论】:

    【解决方案2】:

    如果要从堆中获取内存,可以这样使用:

    // declaration
    char *dog = new char[640*480];
    
    // usage
    dog[first_index * 640 + second_index] = 'a';
    
    // deletion
    delete[] dog;
    

    【讨论】:

    • 我认为像这样的索引方案几乎总是比直接处理二维数组更可取。
    • 2D 数组与 1D 数组的开销是多少?它会减慢速度吗?
    • @Yappie - 谢谢,已修复。
    • @jdl:不应该有任何开销,但这对某些事情来说更快,而在其他事情上更容易出错。
    【解决方案3】:

    您正在使用** 创建指向指针的指针。我不确定你想要那个,你可能想要一个普通的指针 (*)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-27
      相关资源
      最近更新 更多