Question

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!

Was it helpful?

Solution 2

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>?

OTHER TIPS

You need to call the constructor of the objects before you can use them. If you insist in using calloc() you'll need to use placement new to construct the object, e.g.:

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

Note that you will also need to destroy the object later, e.g.:

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

The conventional way is not to use the C memory management functions at all and rather use new[] in the first place:

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

The C++ memory operators deal with construction/destruction as needed. To get entirely rid of the explicit memory management, you'd actually just use a std::vector<std::string>:

std::vector<std::string> strs(counts);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top