Thread: problem with allocation.

  1. #1
    wrong_guy
    Guest

    problem with allocation.

    hello.

    i can do that

    int i=5;
    int p=new int [i];

    i want to do that

    int i=5,j=9;
    int p=new int [i][j];

    how can i do it?

    thanks.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    > int i=5;
    > int p=new int [i];
    Should be
    int *p = new int[i];

    > int i=5,j=9;
    > int p=new int [i][j];
    Should be
    int **p = new int*[i];
    for ( int r = 0 ; r < i ; r++ ) p[i] = new int[j];

    Basically, you allocate one level of indirection at a time.

    However, if 'j' was constant in your example, then you could do this
    int i=5; const int j=9;
    int (*p)[j] = new int[i][j];

    Either way, you can use p[x][y] to access individual elements.
    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.

  3. #3
    I lurk
    Join Date
    Aug 2002
    Posts
    1,361
    Code:
    int **p;
    int x = 5;
    int y = 9;
    
    // Allocate it
    p = new int*[x];
    
    for (int i = 0; i < x; i++)
    	ptr[i]=new int[y];
    
    //... Do something with it
    
    
    // Delete it
    for(int j = 0; j < x; j++)
    	delete [] ptr[j];
    
    delete ptr;

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. searching problem
    By DaMenge in forum C Programming
    Replies: 9
    Last Post: 09-12-2005, 01:04 AM
  2. half ADT (nested struct) problem...
    By CyC|OpS in forum C Programming
    Replies: 1
    Last Post: 10-26-2002, 08:37 AM
  3. memory allocation problem....help..
    By CyC|OpS in forum C Programming
    Replies: 8
    Last Post: 10-18-2002, 09:26 AM
  4. binary tree problem - help needed
    By sanju in forum C Programming
    Replies: 4
    Last Post: 10-16-2002, 05:18 AM
  5. Pointer and memory allocation problem
    By Dual-Catfish in forum C++ Programming
    Replies: 2
    Last Post: 02-17-2002, 11:13 AM