I am having trouble creating an array of strings using calloc. I am unsure if the array is not getting created or not. The program crashes when I try to set the string value:
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;
}
I've also tried using:
strs[i].asign("Hello World");
but I still get a Windows error that "an error has caused the program to stop working correctly"
Any help would be great!
As string
is a C++ class that requires proper initialisation, you can't calloc
it, you must new
it.
strs = new string[counts];
You probably shouldn't be allocing an array of strings in the first place – why not use a std::vector<string>
?