954,504 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Dynamic 2d array not passing?

Hey, im trying to print what is stored in my 2d dynmic array from a file in my print function. However whenever i try to access information in the array, it crashes the program. maybe the array is not being passed back some how, im not sure, any information would be helpful.

In the function getData(), i can output the array.

Attached is all the program files with a test file "data.txt"

Thank you in advance

void getData(int**,int&,int&);
void print(int**,int,int);

int main()
{
  int **array;
  int row, column;
  getData(array,row,column);
  
  print(array,row,column);

  system("PAUSE");
  return 0;
}

void print(int **array, int row, int column)
{
  for(int y=0; y < row; y++)
    {
      cout << endl;
      for(int x=0; x < column; x++)
        {
          cout << array[y][x] << " ";
        }
    }
  cout << endl;
}
    
void getData(int **array, int &row,int &column)
{
  string fileName;
  ifstream data;  
  cout << "Enter File Name\n";
  getline(cin, fileName);
  data.open(fileName.c_str());
  if (!data.is_open())
    cout << "Error opening file\n";
  else
    {
      data >> row >> column;
      array = new int*[column]; //Allocates memory for the array
      for (int q = 0; q < column; ++q)
        array[q] = new int[row];
      for(int y=0; y < column; y++)
        {
          for(int x=0; x < row; x++)
            {
              data >> array[y][x];
            }
        }
    }
  data.close();
}
Attachments Maze.cpp (1.59KB) stack.h (0.55KB) data.txt (0.05KB)
DevC++4.9.9.2
Light Poster
39 posts since Apr 2008
Reputation Points: 10
Solved Threads: 1
 

When you are passing row and col to get Data, you are derefenrencing it. But they are of type int. And what does " >> " operator do? I've never seen it used out side of cin >> .


[edit] er nvm i didn't read your code right.

freudian_slip
Light Poster
36 posts since Oct 2008
Reputation Points: 11
Solved Threads: 4
 

how am i derefrencing it?

DevC++4.9.9.2
Light Poster
39 posts since Apr 2008
Reputation Points: 10
Solved Threads: 1
 

Your getData( ) function is being passed the int ** BY VALUE. It can allocate memory to that pointer variable, but that allocation only exists within the scope of the function. The int ** in main( ) is still not allocated any memory.

So, to make life interesting, you must pass the int** by reference, like:

void getData( int** & ,int&,int&);


Also, in getData( ), you are using the row and column variables backwards. Do the allocations and reading loops with row as the outer loop, column as the inner loop, as you do in your display function.

vmanes
Posting Virtuoso
1,914 posts since Aug 2007
Reputation Points: 1,268
Solved Threads: 228
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You