Creating arrays in C++ without knowing the length ahead of time

前端 未结 3 794
遥遥无期
遥遥无期 2021-01-19 18:14

I\'m working on a small program to help speed up some data analysis for my lab work. It\'s supposed to read in data from a text file, create a bunch of arrays containing thi

3条回答
  •  日久生厌
    2021-01-19 18:47

    You could either use a C++ container, like std::vector, or use dataPoint *data = malloc(LENGTH * sizeof(dataPoint)). In C++, it's probably better practice to use std::vector.

    C99 has variable-length arrays, but you're question seems to be C++.

    The real problem, though, is that you want to slurp the whole file all at once. Unless you're using a library that requires data to be in memory, it'll probably be easier to iterate over the text of the file using fgetc or whatever C++ has for that. After all, you'll need to go through the text at some point; you might as well save yourself the trouble of allocating memory.

提交回复
热议问题