【问题标题】:C++ arrays , and the "new" keywordC++ 数组和“new”关键字
【发布时间】:2017-08-05 12:51:40
【问题描述】:

所以我在这里有这段代码,我尝试创建一个不同大小的二维数组, 首先我声明了 3 个指针,然后我为它们分配了不同的数组,希望它能正常工作并且做得很好,但是有问题,在第二个代码中编译器给出了一个错误(int* 类型的值不能分配给实体输入int )所以这意味着它们不再是我认为的指针,但是为什么会这样,我在这里缺少什么?除了其中一个在堆栈中声明而另一个在堆上之外,这两个代码的最大区别是什么

int main()
{
   int* arr[3];
   arr[0] = new int[5];
   arr[1] = new int[2];
   arr[2] = new int[6];

  delete[] arr[0];
  delete[] arr[1];
  delete[] arr[2];
}

//第二个代码

int main()
{
   int* arr = new int[3];
   arr[0] = new int[5];
   arr[1] = new int[2];
   arr[2] = new int[6];

}

对不起我的英语不好

【问题讨论】:

  • 应该是int** arr = new int*[3];
  • 不要做你现在正在做的事情,也不要使用嵌套向量,而是实现一个适当的二维数组。例如阅读this answer
  • @BaummitAugen:OP 不想要他的 sn-p 中的矩阵。所以vector<vector<int>>在这里似乎更合适。
  • @Jarod42 哦,对了。我的阅读很差。对不起你和罗恩。
  • @BaummitAugen 别提了。我现在删除的评论是使用向量的向量。

标签: c++ arrays pointers


【解决方案1】:

在第一个程序中声明了一个指针数组

int* arr[3];

在第二个程序中分配了一个整数数组

int* arr = new int[3];

例如表达式

arr[0]

类型为int

如果你想分配一个指针数组,你应该写

int ** arr = new int *[3];
    ^^               ^

在这种情况下是表达式

arr[0]

有类型int *,你可以写

arr[0] = new int[5];

【讨论】:

    猜你喜欢
    • 2022-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-28
    • 2014-12-02
    • 2015-10-12
    • 2012-08-12
    相关资源
    最近更新 更多