Reputation: 1
I'm writing an algorithm with NTL library(it's a C++ library). Now I have N files to edit and I have to create/open them at the same time. I try to dynamically allocate space for the N file pointers but there's something wrong with the code. The code snippet is shown below:
P1 = (char **)calloc(n+1, sizeof(char *));//P1 is used to save file names
for(i=1; i<=n; i++)
{
P1[i]=(char *)calloc(20, sizeof(char ));
sprintf(P1[i],"P1_%d.txt",i);
}
ifstream *fin = (ifstream *)calloc(n+1, sizeof(ifstream));
for(i=1; i<=n; i++)
{
fin[i].open(P[i]);
}
When the program runs in linux, it tells me there is a Segmentation Fault.
Since N is not larger than 200, when I try to use
ifstream fin[200]
instead of
ifstream *fin = (ifstream *)calloc(n+1, sizeof(ifstream));
the program runs.
I just learned C but not C++, and I don't really know how the fstream
class works. Could you tell me if there is some better ways to open N files at the same time?
Upvotes: 0
Views: 1518
Reputation: 55887
calloc
will just alloc memory, but ifstream
is complex type. It has constructor, that should be called on object creation. I think you should read some docs/book about C++. You should allocate memory in C++ using new expression. Btw, it's better to use smart pointers (such as unique_ptr) if you use modern C++ compiler. Also, it's much better to use vector, when you want to store unknown on compile-time count of objects. In this case it will be simpler to just use vector<ifstream>
.
// includes for vector and unique_ptr.
#include <vector>
#include <memory>
vector<ifstream> streams;
for (int i = 0; i < n; ++i)
{
streams.push_back(ifstream(P[i]));
}
Upvotes: 5