2014-01-30 100 views
0

我无法使用calloc创建字符串数组。我不确定数组是否未被创建。程序崩溃时,我尝试设置字符串值:C++ calloc字符串数组

using namespace std; 

int main(void){ 
    int counts; 
    string* strs; 

    cout<<"Enter a number: "; 
    cin>>counts; 
    cout<<endl; 

    strs=(string*)calloc(counts,sizeof(string)); 

    for(int i=0;i<counts;i++){ 
      strs[i] = "Hello World!"; 
      cout<<i<<") "<<strs[i]<<endl; 
    } 

    return 0; 
} 

我使用也尝试:

strs[i].asign("Hello World"); 

,但我仍然得到一个Windows错误“的错误导致程序停止正常工作“

任何帮助将是伟大的!

回答

3

由于string是一个C++类,需要正确的初始化,你不能calloc它,你必须new它。

strs = new string[counts]; 

你可能不应该allocing字符串数组摆在首位 - 为什么不使用std::vector<string>

4

您需要先调用对象的构造函数才能使用它们。如果您在使用calloc()坚持,你将需要使用新的布局构造对象,如:

#include <new> 
// ... 
new(strs + i) std::string("Hello World!"); 

请注意,您还需要稍后销毁对象,例如:

strs[i].~std::string(); 

的传统方式是在所有摆在首位使用C内存管理功能,而使用new[]

string* strs = new std::string[counts]; 
// ... 
strs[i] = "Hello World!"; 
// ... 
delete[] strs; 

C++内存操作符根据需要处理构建/销毁。为了完全摆脱显式内存管理,你实际上只需要使用一个std::vector<std::string>

std::vector<std::string> strs(counts);