请帮助我,我无法理解这段代码是如何工作的。 我似乎无法在脑海中想象它。详尽的解释可以避免我将来成为失败者的麻烦。谢谢。
int **data = new int*[row];
for(i=0;i<row;i++)
data[i] = new int[col];
for(i=0;i<row;i++)
{
for(j=0;j<col;j++)
{
data[i][j] = rand() % u;
}
}
最佳答案
#include <cstddef> // std::size_t
#include <cstdlib> // std::srand(), std::rand()
#include <ctime> // std::time()
int main()
{
// Initialize the random number generator with the current time.
// If you don't, std::rand() behaves as if std::srand(1) had been called.
std::srand(static_cast<unsigned>(time(nullptr)));
std::size_t rows = 5;
std::size_t cols = 10;
int u = 100;
int **data = // data is a pointer to a pointer to int
new int*[rows]; // allocates an array of type int* with size of row
// and return a pointer to it
for (std::size_t i = 0; i < rows; i++)
data[i] = // every pointer in that array is assigned
new int[cols]; // a pointer to an array of type int with size col
for (std::size_t i = 0; i < rows; i++) // walk through the (int**) in data
{
for (std::size_t j = 0; j < cols; j++) // walk through the (int*) in data[i]
{
data[i][j] = std::rand() % u; // access the j th int in data[i]
}
}
// free the memory, when you are done using it *):
for (std::size_t i = 0; i < rows; i++)
delete[] data[i];
delete[] data;
}
*) 更好:使用智能指针,例如 std::unique_ptr
和 std::shared_ptr
,这样您就不必关心资源管理:
#include <memory>
// ...
auto data = std::make_unique<std::unique_ptr<int[]>[]>(rows);
for (std::size_t i = 0; i < rows; i++)
data[i] = std::make_unique<int[]>(cols);
甚至更好:使用像 std::vector
或 std::deque
这样的容器。
关于c++ - 迷失在指针的世界里,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52545297/