C++ 使用 "new" 或其他创建动态数组的方法创建类似静态数组
c++ creating a static like array with "new" or another way of creating a dynamic array
我知道在c++中使用new
创建动态数组的常用技术是:
int * arr = new int[5];
一本书还说:
short tell[10]; // tell is an array of 20 bytes
cout << tell << endl; // displays &tell[0]
cout << &tell << endl; // displays address of the whole array
short (*p)[10] = &tell; // p points to an array of 20 shorts
现在我想知道是否有一种方法为使用new
的数组分配内存,因此它可以被分配给指向整个数组的指针。可能看起来像这样:
int (*p)[5] = new int[5];
上面的例子不起作用。我看左边是正确的。但是我不知道右边应该是什么。
我的目的是了解这是否可能。我知道有std::vector
和std::array
。
更新:
下面是我想检查的内容:
int (*p1)[5] = (int (*)[5]) new int[5];
// size of the whole array
cout << "sizeof(*p1) = " << sizeof(*p1) << endl;
int * p2 = new int[5];
// size of the first element
cout << "sizeof(*p2) = " << sizeof(*p2) << endl;
下面是访问这些数组的方法:
memset(*p1, 0, sizeof(*p1));
cout << "p1[0] = " << (*p1)[0] << endl;
memset(p2, 0, sizeof(*p2) * 5);
cout << "p2[0] = " << p2[0] << endl;
知道创建动态数组的常用技术
在20年前写的c++里,也许。
这些天你应该使用std::vector
动态数组和std::array
固定大小的数组。
如果您的框架或平台提供了额外的数组类(如QT的QVector
),它们也很好,只要您不直接与c指针混淆,并且您有基于raii的数组类。
,至于具体的答案,new T[size]
总是返回T*
,所以你不能用T(*)[size]
捕获new[]
返回的指针。
问题是左右视线有不同的类型。
类型:
new int[5]
int*.
类型:
int (*p)[5]
int (*)[5].
编译器不能将它们赋值给另一个
一般来说,不可能将T*
赋值给T (*)[N]
。这就是为什么你需要使用问题开头提到的语法。
相关文章:
- 在c++中为double类型的数组创建一个unique_ptr
- 如何从预定义的数组创建某些元素数组
- 基于数组的列表 - 动态数组创建时出错
- 从 UTF-8 字节数组创建字符串?
- 是否可以在并行区域中为共享 2D 数组创建选定元素的线程本地副本?(共享,私有,障碍:OPenMP)
- C++ 从名称数组创建对象
- 从数组创建 Mat 时,'cv::Mat' 和 'int' 类型不兼容
- 从 std::数组创建十六进制代表
- 在 C++ 结构内声明的数组 A[1] 创建多个实例
- 为多维数组创建内存空间
- 如何使用任何类型的数组创建模板类并为其设置值?
- 从字符串数组创建一个字符数组
- 是否可以在不为该数组创建变量的情况下将数组作为参数传递到函数中?
- 使用类定义数组创建C++类
- 使用具有唯一随机数的结构数组创建多个对象
- 谷歌测试:无法从字符数组创建字符串
- 从 1D 数组创建 2D 数组
- 无法通过一个单向链表数组创建邻接列表
- 如何使用数组创建标准::函数
- 在C++中,返回从本地字符数组创建的字符串是否会导致内存泄漏或未定义的行为