Reading lines from txt file with calloc

Hi guys I dont have a specific code yet.
I know how to read a txt file with fstream. I can implement a program which reads and gives out the lines. My question now is how can i save the lines in arrays and give out a specific amount of lines afterwards with calloc and malloc.(I dont understand how to use them) Already looked up the tutorial but i dont understand it.
You really shouldn't be using malloc/calloc in C++. I would suggest using std::vector instead of arrays.


I think there is a way to directly read text into a c++ string... hang on ... i had some trouble with it but that was probably me doing something dumb. But if you want a vector of strings, just do that with getline calls, there isnt anything cleaner that I know of.

calloc is just a gibberish way to write
type * t = new type[size]; //c++ memory management, usually avoided.
instead you write
type *t = (type*) calloc(size, sizeof(type)); //same thing, but C instead of C++
both of which are inferior to
vector<type> t(size); //reserves size amount of space, can still grow to add more if needed.

malloc is similar, but you do your own multiply, calloc does that for you with 2 args, which is exceedingly redundant but no one asked me.

type*t = (type*)malloc(size*sizeof(type));

malloc and calloc pair to free() to clean up the memory.
new pairs to delete. you cannot mix and match these.
vector self cleans, nothing to do, as with all c++ containers.

there is a time to use these in low level c++. If you need to resize memory, the C ones allow realloc. Doing this should be rather rare, but its a tool if you need it.
Last edited on
Registered users can post here. Sign in or register to post.