Thread: 2D array syntax

  1. #1
    Registered User
    Join Date
    Nov 2010
    Posts
    5

    Unhappy 2D array syntax

    How can i declare a 2 D array in Visual Studio C++ 6.0 ?
    my code is giving errror;


    Code:
    class sparseadd
    {
    	int *p;
    	int row;
    	int col;
    	struct node
    	{
    		int val;
    	};
    
    	public:
    	sparseadd(int, int );
        
    
    };
    sparseadd::sparseadd(int r, int c)
    {
    	row = r;
    	col = c;
    	p = new int [r][c];
    }

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    You're not declaring a two dimensional array, you're simulating one with dynamic memory and pointers:
    Code:
    // Declaration
    int **p;
    Code:
    // Constructor
    p = new int[r];
    
    for (int i = 0; i < row; i++)
        p[i] = new int[col];
    Code:
    // Destructor
    for (int i = 0; i < row; i++)
        delete[] p[i];
    
    delete p;
    p.s. I strongly recommend you ditch Visual C++ 6.0. It's very crappy as a C++ compiler.
    My best code is written with the delete key.

  3. #3
    Registered User
    Join Date
    Nov 2010
    Posts
    5
    yeah it worked out well!but now how i will pass this 2 D array as a function parameter if i have to decide on runtime the colommn size of the array after reading from the file?

  4. #4
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >how i will pass this 2 D array as a function parameter if i have to decide on runtime the colommn size of the array
    That's the whole point of simulating an array in this case. You're using a pointer to a pointer (which doesn't require any dimension sizes) and can pass it to a function as-is. Though I'd recommend passing the size as well, in separate parameters:
    Code:
    void foo(int **p, int rows, int cols);
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Swapping Rows and Columns in a 2D array
    By xxshankar in forum C Programming
    Replies: 2
    Last Post: 03-11-2010, 03:40 PM
  2. question about multidimensional arrays
    By richdb in forum C Programming
    Replies: 22
    Last Post: 02-26-2006, 09:51 AM
  3. linked list inside array of structs- Syntax question
    By rasmith1955 in forum C Programming
    Replies: 14
    Last Post: 02-28-2005, 05:16 PM
  4. Learning OpenGL
    By HQSneaker in forum C++ Programming
    Replies: 7
    Last Post: 08-06-2004, 08:57 AM
  5. Replies: 6
    Last Post: 10-21-2003, 09:57 PM

Tags for this Thread