[英]How to just use "new" for a pointer of which type is int[3]?
我不太明白你想问什么,但在cppreference中,有
new 表达式返回一个指向构造的 object 的纯右值指针,或者,如果构造了对象数组,则返回“指向数组初始元素的指针”。
因此, new int[1][3]
返回一个指向数组初始元素的指针,这意味着类型是int[3]
。 所以你可以用它来初始化指针int(*p)[3]
,它的类型是int(*)[3]
我想它可能会对你有所帮助。
正如退休的忍者所说,使用结构,如果可以的话,也尽量避免新建/删除。 (特别是对于您将在编译时知道其大小的数组)。 这是一个例子:
#include <array>
#include <iostream>
#include <memory>
// Always try to model things that have a name
// in the real world. Seperates the "How" (implementation details, in your case an array of values)
// from the "What" (what does your code represent)
// and reading code that has a
struct point_t
{
// initialize all values to defaults
int x{};
int y{};
int z{};
};
// again the array is HOW you would implement it
// but what you are doing is defining a matrix
// so give it a name/type
struct matrix_t
{
point_t values[3][3];
};
// you don't have to use pointers to pass matrices
// around by copying if you use references
// The const is there because show_matrix should
// NOT be able to modify the content of the matrix
// https://www.learncpp.com/cpp-tutorial/references/
void show_matrix(const matrix_t& matrix)
{
// use range based for loops (unless you need the indices explicitly)
// range based for loops can't go out of bounds
// loop over the rows
// https://en.cppreference.com/w/cpp/language/range-for
for (const auto& row : matrix.values)
{
bool comma = false;
// then loop over the values in the row
for (const auto& point : row)
{
if (comma) std::cout << ", ";
// normally I would overload operator<< for point_t
std::cout << "(" << point.x << ", " << point.y << ", " << point.z << ")";
comma = true;
}
std::cout << "\n";
}
}
int main()
{
// in c++ avoid new/delete if you can. (they're a main cause for bugs:
// memory leaks, use after free, unitialized pointers (access violations) etc.)
// specially if you now the sizes at compile time.
//
// Read the following document
// https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines
// and look for new/delete and pointers
matrix_t points;
show_matrix(points);
// if you really need to allocate dynamically
// then use std::make_unique instead of new/delete
// https://en.cppreference.com/w/cpp/memory/unique_ptr/make_unique
auto matrix_ptr = std::make_unique<matrix_t>();
show_matrix(*matrix_ptr);
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.