[英]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.