开发者

How to initialize c-strings array (no stl)

开发者 https://www.devze.com 2023-03-08 10:33 出处:网络
I want to initialize array of c-strings with zero pointers in MSVC2010 // Foo.h #pragma once class Foo {

I want to initialize array of c-strings with zero pointers in MSVC2010

// 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 hav开发者_如何学运维e to initialize arr_ (dynamic array and can be enlarged later)
  arr_ = (char **)calloc(INITIAL_SZ * sizeof (char *)); // ??? 
  // or maybe arr_ = new ...
}

How to correct initialize arr_? I was not allowed to use of STL, MFC, etc.


arr = new char*[INITIAL_SZ](); will do - you can even put it in an initialization list.


If you really want to avoid STL, etc., then why not:

arr_ = new char*[INITIAL_SZ]();

You could even put this in the initializer list.

Remember to invoke delete [] arr_ in your destructor. (As @Nawaz points out below, you should probably also follow the Rule of Three, and define a suitable copy-constructor and assignment operator as well.)


1. Build a proper string class

2. Build a proper array class

3. Use the array on strings

Happy chasing memory leaks, double frees and memory corruption.


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

should be

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


The correct way is to redefine arr_ as std::vector<std::string> and to use vector::reserve() to hint at the number of strings you expect to have. Let C++ take care of the memory for you.

But if you must use raw C strings, you probably want:

arr_ = new char *[sz_];
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号