Dynamic two dimensional arrays

This is a discussion on Dynamic two dimensional arrays within the C++ Programming forums, part of the General Programming Boards category; I have a problem declareing dynamic two dimensional arrays. In addition, I want to initialize all of the array's elements ...

  1. #1
    Registered User
    Join Date
    Aug 2006
    Location
    Israel
    Posts
    33

    Dynamic two dimensional arrays

    I have a problem declareing dynamic two dimensional arrays. In addition, I want to initialize all of the array's elements to 0, but I can't seem to do so.

    This is basically my code:
    Code:
    cout << "Enter a number\n";
    cin >> n;
    int *arr = new int [n][n] = {{0},{0}};
    Yet, the compiler generates an error. Whats wrong with the code?
    Thank you

  2. #2
    Registered User major_small's Avatar
    Join Date
    May 2003
    Posts
    2,787
    umm... yuck.

    Code:
    #include <iostream>
    
    int main()
    {
    	/*
    	 * These are garbage data to fill the array
    	 */
    	int a=1;
    	int b=2;
    	int c=3;
    	int d=4;
    
    	/*
    	 * This is the size of the array... put this in an I/O
    	 * statement/response if you wish
    	 */
    	int x=2;
    	int y=2;
    	
    	/*
    	 * create an array of pointers to pointers, then point each pointer
    	 * to a pointer to a new pointer
    	 */
    	int**arr=new int*[x];
    	for(int i=0;i<x;i++)
    	{
    		arr[i]=new int[y];
    	}
    
    	/*
    	 * fill the array with the garbage data
    	 */
    	arr[0][0]=a;
    	arr[0][1]=b;
    	arr[1][0]=c;
    	arr[1][1]=d;
    
    	/*
    	 * output the array
    	 */
    	for(int o=0;o<2;o++)
    	{
    		for(int i=0;i<2;i++)
    		{
    			std::cout<<arr[o][i]<<std::endl;
    		}
    	}
    
    	/*
    	 * free up the memory (I was too lazy, but this CAN NOT be skipped)
    	 */
    	
    	return 0;
    }
    oh yeah... dont' forget to free up the memory too

    it's been a while since I've touched code, so forgive any retartedness in there
    Last edited by major_small; 08-29-2006 at 12:13 PM.
    Join is in our Unofficial Cprog IRC channel
    Server: irc.phoenixradio.org
    Channel: #Tech


    Team Cprog Folding@Home: Team #43476
    Download it Here
    Detailed Stats Here
    More Detailed Stats
    52 Members so far, are YOU a member?
    Current team score: 1223226 (ranked 374 of 45152)

    The CBoard team is doing better than 99.16% of the other teams
    Top 5 Members: Xterria(518175), pianorain(118517), Bennet(64957), JaWiB(55610), alphaoide(44374)

    Last Updated on: Wed, 30 Aug, 2006 @ 2:30 PM EDT

  3. #3
    Registered User
    Join Date
    Jan 2005
    Posts
    7,328
    In C++ you should use a vector or some other container instead of C style arrays. Here's the code for vector that creates the 2-d array and initializes the values to 0:
    Code:
    std::vector<std::vector<int> > arr(n, std::vector<int>(n));

  4. #4
    Registered User
    Join Date
    Aug 2006
    Posts
    4

    Smile Here's a complete code for making dynamic 2d array

    As you must be knowing that in arrays whether single or multidimensional, elements of arrays are stored in contigious memory location.So for building a dynamic two dimensional array i would suggest u to use a single dimensional dynamic array. Here is a simple program for ur better understanding
    Code:
    #include<iostream>
    using namespace std;
    
    int main()
    {
    int row,col;
    int *arr;
    cout<<"\nEnter number of rows";
    cin>>row;
    cout<<"\nEnter number of columns";
    cin>>col;
    
    //create array large enough to hold our 2D array
    arr = new int[row*col]
    
    //insert elements
    for(int i=0;i<row;i++)
         for(int j=0;j<col;j++)
              cin>>arr[(i*col)+j];
    
    cout<<endl<<endl;
    
    //display elements
    for(i=0;i<row;i++)
    {
         for(j=0;j<col;j++)
              cout<<arr[(i*col)+j];
         cout<<endl;
    }
    return 0;
    }
    note that to see how this single array works as a 2D array i would suggest you to take a paper and pencil and compute the values of arr[(i*col)+j] for different values of i and j. The program is write but still check for syntax errors.
    Last edited by Salem; 08-29-2006 at 01:48 PM. Reason: code tags added - please learn how to use them

  5. #5
    Registered User
    Join Date
    Jan 2005
    Posts
    7,328
    That code isn't actually complete. In fact, what it is missing is one of the biggest reasons you should be using vector instead of dynamic arrays. If you want all the memory to be contiguous you can use the same technique with a vector.

  6. #6
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,592
    Dynamic, contiguous and with traditional 2-subscript access.
    Code:
    #include<iostream>
    using namespace std;
    
    int main()
    {
      int row,col;
      int **arr;
    
      cout<<"\nEnter number of rows";
      cin>>row;
      cout<<"\nEnter number of columns";
      cin>>col;
    
      //create array large enough to hold our 2D array
      arr = new int*[row];
      arr[0] = new int [row*col];
      for ( int i = 1 ; i < row ; i++ ) {
        arr[i] = arr[i-1] + col;
      }
    
      //insert elements
      for(int i=0;i<row;i++)
           for(int j=0;j<col;j++)
                cin>>arr[i][j];
    
      //display elements
      for(int i=0;i<row;i++)
      {
           for(int j=0;j<col;j++)
                cout<<arr[i][j];
           cout<<endl;
      }
      
      delete [] arr[0];
      delete [] arr;
    
      cin.ignore(numeric_limits<streamsize>::max(),'\n');
      cin.get();
      return 0;
    }
    Now use a vector.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  7. #7
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,893
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  8. #8
    Super Moderator VirtualAce's Avatar
    Join Date
    Aug 2001
    Posts
    9,596
    I say use one of the three: linear array, vector, or one of the boost arrays. But please don't use a 2D array. And please don't use a 2D vector.

    Simple solution is to use a linear array and access it in two dimensions. Vectors are a much better choice if you don't know how many elements you need.

  9. #9
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    >Dynamic, contiguous and with traditional 2-subscript access.
    Neat. Makes passing 2-D contiguous arrays as easy as it is in Fortran.

  10. #10
    Registered User
    Join Date
    Jan 2005
    Posts
    7,328
    >> But please don't use a 2D array. And please don't use a 2D vector.
    Is it really necessary to make this optimization at the expense of the extra complexity? I don't think so.

  11. #11
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,893
    Jagged arrays have enough complexity of their own, especially vectors of vectors. Like having to resize each vector individually if you want to resize the inner dimension.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  12. #12
    Registered User major_small's Avatar
    Join Date
    May 2003
    Posts
    2,787
    Dynamic, contiguous and with traditional 2-subscript access.

    what, no bounds checking?
    j/k, I bow to thee.
    Join is in our Unofficial Cprog IRC channel
    Server: irc.phoenixradio.org
    Channel: #Tech


    Team Cprog Folding@Home: Team #43476
    Download it Here
    Detailed Stats Here
    More Detailed Stats
    52 Members so far, are YOU a member?
    Current team score: 1223226 (ranked 374 of 45152)

    The CBoard team is doing better than 99.16% of the other teams
    Top 5 Members: Xterria(518175), pianorain(118517), Bennet(64957), JaWiB(55610), alphaoide(44374)

    Last Updated on: Wed, 30 Aug, 2006 @ 2:30 PM EDT

  13. #13
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,592
    > what, no bounds checking?
    Of course there is, step too far out of bounds and it will segfault
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  14. #14
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    >Of course there is, step too far out of bounds and it will segfault
    I think kids these days want a happy fuzzy warning rather than a mean old fashioned segfault.
    My best code is written with the delete key.

  15. #15
    Registered User
    Join Date
    Jan 2005
    Posts
    7,328
    Or maybe just an out_of_range exception.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Creating and freeing dynamic arrays
    By circuitbreaker in forum C++ Programming
    Replies: 8
    Last Post: 02-18-2008, 10:18 AM
  2. Replies: 16
    Last Post: 01-01-2008, 03:07 PM
  3. processing dynamic arrays
    By Mario F. in forum C++ Programming
    Replies: 9
    Last Post: 06-04-2006, 11:32 AM
  4. Dynamic (Numeric) Arrays
    By DavidB in forum C++ Programming
    Replies: 5
    Last Post: 05-03-2006, 07:34 PM
  5. Two dimensional arrays
    By Jax in forum C Programming
    Replies: 1
    Last Post: 11-07-2001, 11:53 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21