srgg6701
srgg6701

Reputation: 2048

C++ the dynamic array and file reading don't work together

Such a code:

int _tmain(int argc, _TCHAR* argv[])
{
    int *test = new int[];
    ifstream f("ofile.txt");
    for (int i=0,v; i<10; i++)
    {
        f>>v;
        test[i]=1; 
        cout<<"\nv = "<<v<<", i = "<<i<<endl;
    }

    return 0;
}

caused of this message after compiling:

enter image description here

I guess (correct me if I'm wrong) here is some error about memory, but details are unknown for me. If I remove one of them (file reading or array) it works. So it will be great to hear an explanation of the problem.

Upvotes: 0

Views: 223

Answers (2)

Michael J
Michael J

Reputation: 7949

You're thinking java. To allocate an array like that you need to give a size. e.g.

    int *test = new int[20];

However a better scheme would be to use a vector of integers.

    #include <iostream>
    #include <fstream>
    #include <vector>
    #include <algorithm>  // for sort()

    int main(int argc, char *argv[])
    {
        std::vector<int> data;
        std::ifstream fsin("ofile.txt");

        int count = 0;
        while (fsin.good())
        {
            int v;
            fsin >> v;
            if (fsin.good())
            {
                data.push_back(v);
                std::cout << "\nv = " << v << ", i = " << count++ << std::endl;
            }
        }

        std::sort(data.begin(), data.end());

        for (size_t i=0; i<data.size(); i++)
            std::cout << i << '\t' << data[i] << std::endl;

        return 0;
    }

Upvotes: 5

OneOfOne
OneOfOne

Reputation: 99371

You have to allocate a fixed size array, int *test = new int[]; shouldn't even work.

If the size is known, use int *test = new int[size];, otherwise try using a std::vector or std:array.

Upvotes: 3

Related Questions