0

我想在 MSVC2010 中用零指针初始化 c 字符串数组

// Foo.h
#pragma once
class Foo {
  int sz_;
  char **arr_; 
public:
  Foo();
  ~Foo();
  // ... some other functions
};

// Foo.cpp
#include "Foo.h"
#define INITIAL_SZ 20

Foo::Foo() : sz_(INITIAL_SZ) {
  // there I have to initialize arr_ (dynamic array and can be enlarged later)
  arr_ = (char **)calloc(INITIAL_SZ * sizeof (char *)); // ??? 
  // or maybe arr_ = new ...
}

如何正确初始化arr_?我不允许使用 STL、MFC 等。

4

5 回答 5

5

arr = new char*[INITIAL_SZ]();会做 - 你甚至可以把它放在一个初始化列表中。

于 2011-05-26T17:39:25.320 回答
4

如果你真的想避免 STL 等,那何乐而不为:

arr_ = new char*[INITIAL_SZ]();

你甚至可以把它放在初始化列表中。

记得在你的析构函数中调用delete [] arr_。(正如@Nawaz 在下面指出的那样,您可能还应该遵循三法则,并定义一个合适的复制构造函数和赋值运算符。)

于 2011-05-26T17:40:14.017 回答
2

1.构建合适的字符串类

2.构建合适的数组类

3.在字符串上使用数组

快乐地追逐内存泄漏、双重释放和内存损坏。

于 2011-05-26T17:41:44.973 回答
1
arr_ = (char **)calloc(INITIAL_SZ * sizeof (char *));

应该

arr_ = (char **)calloc(INITIAL_SZ, sizeof (char *));

于 2011-05-26T17:40:07.897 回答
1

正确的方法是重新定义arr_asstd::vector<std::string>并使用vector::reserve()来提示您希望拥有的字符串数量。让 C++ 为您处理内存。

但是如果你必须使用原始 C 字符串,你可能想要:

arr_ = new char *[sz_];
于 2011-05-26T17:40:33.477 回答