Dynamically Allocated 2-d array

Working on a program for a friend of mine to change a .txt file. I was hoping to get some advice on my program as I seem to always end up in an infinite loop while I'm printing out the data. Here's what I have so far:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
#include <fstream>

using namespace std;

int main()
{
    int count=0;
    ifstream myFile;
    myFile.open("data.txt");
    while(!myFile.eof()) //open file to get count
        {
        myFile.get();
        count++;
        }
    myFile.close();
    int **marina = new int *[count];
    for(int z=0;z<count; z++)
    {
        marina[z] = new int [14];
    }
    myFile.open ("data.txt"); //had to reopen file to read into
    for(int i=0; i<count;i++)        //array
    {
        for(int c=0;c<14;c++)
        {
            marina[i][c] = myFile.get();
        }
    }
    myFile.close();
    for (int b=0;b<count;b++)        //This is the problem, when trying to see what the data
    {                                //looks like by cout it so I can manipulate it
        for(int y=0;y<14;y++)        //I end up in a infinite loop
        {
            cout << marina[b][y];
        }
    }

    return 0;
}


Looking for any advice, this is my first time working with 2d dynamically allocated arrays.
1
2
3
4
5
6
7
8
9
    int count=0;
    ifstream myFile;
    myFile.open("data.txt");
    while(!myFile.eof()) //open file to get count
        {
        myFile.get();
        count++;
        }
    myFile.close();


So, we've just determined that there are count elements in myFile.


int **marina = new int *[count];

A little confused. We've just allocated space for count pointers to int.


1
2
3
4
    for(int z=0;z<count; z++)
    {
        marina[z] = new int [14];
    }


And now we allocate count arrays of type int and size 14.

So, to recap: There are count byte-sized elements in the file. We've allocated room for count * 14 greater-than-byte-sized elements.

I'm further confused.

1
2
3
4
5
6
7
8
9
    myFile.open ("data.txt"); //had to reopen file to read into
    for(int i=0; i<count;i++)        //array
    {
        for(int c=0;c<14;c++)
        {
            marina[i][c] = myFile.get();
        }
    }
    myFile.close();


We attempt to read in count * 14 elements after we've determined there are only count elements in the file. I'm still confused...
I'm trying to make the dynamic array that is [count][14] since the count variable is unknown but the amount of columns is 14. I was trying to figure out how to do the 2d array dynamically since I haven't learned vectors or anything that might make it easier. Hope that clarifies what I'm trying to do, as far as the code that's why I was asking.
Topic archived. No new replies allowed.