在指针指向一个指针字段的场景中访问值,每个指针都指向 int

Access value in the scenario of pointer pointing to a field of pointers each of which pointing to int

以下场景:

int** pToPField = new int* [8];

现在我有一个指向指针字段的指针。每个都指向一个int,对吧?

现在我想分配前两个 int 字段,例如:

*(*(pToPField)) = 1;
*(*(pToPField + 1)) = 2;

或喜欢:

*(pToPField[0]) = 1;
*(pToPfield[1]) = 2;

错误始终是核心转储。我的语法错了吗?我试图从这个问题的第一个答案中找出答案:How do I use arrays in C++? 我运气不好。

此致

你的语法是正确的,但你没有为数组中的指针指向的整数分配任何 space,所以你正在访问你无权访问的随机内存,导致分段错误。

示例:

pToPField[0] = new int;
pToPField[1] = new int;
// and so on...

考虑改用 std::vector

std::vector<int> pToPField(8);

pToPField[0] = 1;
pToPField[1] = 2;
// and so on ...