[英]How to initialize c-strings array (no stl)
我想在 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 等。
arr = new char*[INITIAL_SZ]();
會做 - 你甚至可以把它放在一個初始化列表中。
如果你真的想避免 STL 等,那何樂而不為:
arr_ = new char*[INITIAL_SZ]();
你甚至可以把它放在初始化列表中。
請記住在您的析構函數中調用delete [] arr_
。 (正如@Nawaz 在下面指出的那樣,您可能還應該遵循三法則,並定義一個合適的復制構造函數和賦值運算符。)
1.建立一個合適的字符串class
2.建立一個合適的陣列class
3.在字符串上使用數組
快樂追逐 memory 泄漏、雙重釋放和 memory 損壞。
arr_ = (char **)calloc(INITIAL_SZ * sizeof (char *));
應該
arr_ = (char **)calloc(INITIAL_SZ, sizeof (char *));
正確的方法是將arr_
重新定義為std::vector<std::string>
並使用vector::reserve()
來提示您期望擁有的字符串數量。 讓 C++ 為您處理 memory。
但是,如果您必須使用原始 C 字符串,您可能想要:
arr_ = new char *[sz_];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.