如何为字符指针数组分配内存?
How to allocate memory to array of character pointers?
我想为以下字符指针数组分配内存:
char *arr[5] =
{
"abc",
"def",
"ghi",
"jkl"
};
for (int i = 0; i < 4; i++)
std::cout << "nprinting arr: " << arr[i];
以下不起作用:
char *dynamic_arr[5] = new char[5];
为字符串数组分配内存的方法是什么?
在C++中,有更多的方法可以初始化字符串数组。您可以只使用string
类。
string arr[4] = {"one", "two", "three", "four"};
对于C
中的字符数组,可以使用malloc
。
char *arr[5];
int len = 10; // the length of char array
for (int i = 0; i < 5; i++)
arr[i] = (char *) malloc(sizeof(char) * len);
C和 C++ 语法混淆,不确定您是在尝试使用 C 还是C++。如果您正在尝试使用C++,以下是一种安全的方法。
std::array<std::string, 10> array {};
对于完全动态的,可以使用一个std::vector
。
std::vector<std::string> array;
可能下面是你找到的:
char **dynamic_arr = new char*[5]; //5 is length of your string array
for(int i =0;i<5;i++)
{
dynamic_arr[i] = new char[100]; //100 is length of each string
}
但是与char*
合作是非常麻烦的。我建议您使用 c++ 中的string
库来存储和操作字符串。
由于这是一个C++问题,我建议使用一种惯用的方式来处理固定/可变的文本集合:std::array
或std::vector
和std::string
。
为字符串数组分配内存的方法是什么?
// If you have a fixed collection
std::array<std::string, 4> /* const*/ strings = {
"abc", "def", "ghi", "jkl"
};
或
// if you want to add or remove strings from the collection
std::vector<std::string> /* const*/ strings = {
"abc", "def", "ghi", "jkl"
};
然后,您可以直观地操作strings
,而无需手动处理内存:
strings[2] = "new value for the string";
if (strings[3] == strings[2]) { /* ... */ } // compare the text of the third and fourth strings
auto pos = strings[0].find("a");
// etc.
相关文章:
- 在c++中为我自己的基于指针的数组分配内存的正确方法
- 给定一个指向堆分配内存的指针,智能指针实现如何为其找到合适的释放函数?
- 如果 const 不分配内存,为什么我可以获取 const 的地址?
- 在函数中分配内存时出现问题
- 如何为 std::vector 分配内存,然后稍后为某些元素调用构造函数?
- constexpr new 如何分配内存?
- 在构造函数中分配内存失败是如何冒泡的
- LLVM 传递以在特定地址分配内存
- CudaMalloc 在分配内存时失败
- 为什么它在不分配内存的情况下工作正常
- 为什么在正确解除分配内存时出现内存泄漏?
- 如何通过 malloc 为队列数组分配内存?
- vector是否为std::移动的对象连续分配内存
- 删除类成员的动态分配内存的最佳方法是什么
- 唯一指针是否在堆或堆栈上分配内存?
- 如果不分配内存,我如何能够为变量创建和分配值?
- std::initializer_list 堆是否分配内存?
- 如何按顺序或在指定的地址分配内存?
- 是否可以使用 malloc 为类对象分配内存?
- 迭代器是否分配内存(如指针)?