c++ - 如何初始化这个指针数组?

标签 c++ arrays pointers initialization

我真的不确定它是什么(如果它是指针数组,还是指针数组数组???),但是当我通过调试器踩到它时,它给了我 0xCDCDCDCD,这意味着内存已分配, 但未初始化。谁能告诉我如何初始化它?

谢谢。

char* (*vars)[4];

我试过这样的东西,但它给出了编译错误:

for (int i = 0; i < 4; i++)
    vars[i] = new char*[new char*][4]; // error C2440: 'initializing' : cannot convert from 'char **' to 'unsigned int'

最佳答案

首先,你需要使用cdecl :

declare vars as pointer to array 4 of pointer to char

你如何初始化它取决于你的目标是什么。但是,例如:

// Create a new array
vars = new (char *[1][4]);
// Each element of the array in turn points to an array
for (int i = 0; i < 4; i++) {
    (*vars)[i] = new char[27];
}

...

// Cleanup
for (int i = 0; i < 4; i++) {
    delete [] (*vars)[i];
}
delete [] vars;

最后,永远不要用 C++ 编写这样的代码。总有更好的方法来完成您想要做的任何事情(通常涉及容器和智能指针)。

关于c++ - 如何初始化这个指针数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9728282/

相关文章:

c++ - 循环次数超出我的预期

c++ - 从 C++ xll 返回多维数组到 excel

Javascript 数组到 URL 编码字符串

javascript - Ajax 响应未定义或奇怪

c++ 为什么 decltype(*pointer) 产生一个引用?

c++ - 如何读取一个http请求(一个http代理服务器)

c++ - OpenCV 将所有负值转换为零

c++ - 是否可以在 C 程序中包含 C++ 库?

c - C中矩阵的内存分配

c++ - std::unordered_set 插入获取对象