c++ - 迷失在指针的世界里

标签 c++ c++11 pointers memory-management dynamic

请帮助我,我无法理解这段代码是如何工作的。 我似乎无法在脑海中想象它。详尽的解释可以避免我将来成为失败者的麻烦。谢谢。

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_ptrstd::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::vectorstd::deque 这样的容器。

关于c++ - 迷失在指针的世界里,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52545297/

相关文章:

c++ - 以编程方式关闭 Windows 控制台应用程序 C++

c++ - OO 语言中的继承与处理

c++ - 使用迭代器从字符串中删除特殊字符

c++ - 静态大小的 valarray 实现

c++11 - std::function 是如何为 lambda 构造的

c++ - “error: incompatible types in assignment of” 尝试调整对象指针数组的大小时

c++ - 创建模板参数的默认值变量

c++ - 在 C++ 中,(int *) 和 & 有什么区别?

c - 两个 block 的字典顺序比较

c - 警告 : assignment from incompatible pointer type