c++ - populating char** -


i'm trying read in list of files file. file reading works populating array of char* isn't. works first iteration gets bad pointer on next line. tried vector of strings having problems, think due destructor trying free argv.

char **datafiles = (char**)malloc(0); int filecount = 0;  master.adddatafiles(argv[1],datafiles,filecount);  int manager::adddatafiles(char *filename, char **filelist, int &filecount) {     const int linemax = 64;     struct stat info;     std::ifstream is(filename);     if (is.fail()) return 1;      char buffer[linemax];      while(!is.eof())     {         is.getline(buffer,linemax);         realloc(filelist,sizeof(char**) * (filecount + 1));         filelist[filecount] = (char*) malloc(std::strlen(buffer) + 1);         std::strcpy(filelist[filecount],buffer);         filecount++;     }      return 0; } 

using realloc correctly bit tricky -- can (and sometimes, not always, will) return different pointer 1 passed it, have this:

char **temp = realloc(filelist, sizeof(char**) * filecount+1); if (temp != null)     filelist = temp; else     failed_allocation(); 

also note while (!file.eof()) classic mistake -- won't sense end of file correctly.

i'd revisit vector of strings option though. perhaps post code had, , ask whatever problem(s) encountered it. getting work less work fixing this, , result more solid , understandable.

correct code like:

std::vector<std::string> manager::adddatafiles(std::string const &filename) {     std::ifstream infile(filename.cstr());    std::vector<std::string> filenames;    std::string temp;    while (std::getline(infile, temp))        filenames.push_back(temp);    return filenames; } 

Comments

Popular posts from this blog

apache - Add omitted ? to URLs -

redirect - bbPress Forum - rewrite to wwww.mysite prohibits login -

php - How can I stop spam on my custom forum/blog? -