gpt4 book ai didi

c++ - 初始化和导航字符**

转载 作者:行者123 更新时间:2023-11-30 04:09:16 25 4
gpt4 key购买 nike

好的,考虑一下这段代码:

char** pool = new char*[2];
pool[0] = new char[sizeof(char)*5];

据我所知,这会创建一个指向 2 个字符指针数组的指针。然后第二行将这 2 个字符指针中的第一个设置为 5 个字符数组中的第一项。如果我错了,请纠正我。

如果我没记错的话:

  1. 我将如何初始化所有这些字符?
  2. 如何更改特定字符?例如,将每个数组中的最后一个字符设置为 NULL。

最佳答案

As far as I know, this creates a pointer to an array of 2 char pointers. [...]

char** pool = new char*[2];

不,该行创建了一个指向字符指针的指针。右侧的表达式创建了一个包含 2 个指向字符的指针的数组。您可以使用指针数组将其初始化为双指针,因为右侧将衰减为双指针。

The second line then sets the first of these 2 char pointers to the first item in an array of 5 chars. [...]

pool[0] = new char[sizeof(char)*5];

“这两个字符指针中的第一个”是什么意思?您只分配给该行上的一个指针。

How would I go about initializing all of these chars?

通过使用循环遍历指针并为它们分配有效内存。

How would I change a specific char? For example, setting the last char to NULL in each array.

for (char** p = pool; p != (pool + 2); ++p)
{
*p = new char[/* amount of chars */];
(*p)[/* amount of chars */] = '\0';
}

但这完全是一团糟。使用字符串 vector 会容易得多:

std::vector<std::string> pool;

关于c++ - 初始化和导航字符**,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21356607/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com