CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    May 1999
    Location
    Israel
    Posts
    16

    2d character array dynamic allocation

    I want to allocate a two dimensional character array dynamically. I tried with various methods and failed.
    buffer[max][30];
    max is a variable so I want to allocate dynamically. Is anyone there to help. Thanks in advance.
    Joel.


  2. #2
    Guest

    Re: 2d character array dynamic allocation

    You should be able to do:

    char** ppBuffer = new char*[nWidth];
    for( int c = 0; c < nWidth; c++ )
    {
    ppBuffer[ c ] = new char[ nHeight ];
    }

    //do stuff...

    delete [ ] [ ] ppBuffer;






  3. #3
    Join Date
    May 1999
    Location
    Israel
    Posts
    16

    Re: 2d character array dynamic allocation

    Thanks I got it. But a sball correction in delete.

    char** ppBuffer = new char*[nWidth];
    for( int c = 0; c < nWidth; c++ )
    {
    ppBuffer[ c ] = new char[ nHeight ];
    }
    //do stuff...
    for( int c = 0; c < nWidth; c++ )
    {
    delete [] ppBuffer[ c ];
    }

    delete [ ] ppBuffer;

    This is working Fine.

    Joel.



  4. #4
    Join Date
    May 1999
    Posts
    3

    Re: 2d character array dynamic allocation

    Hi Joel,

    the solution with everything allocated dynamically is necessary only if you don't know the length of the strings from which you want to build an array at compilation time. However, since in your example you know the second dimension (30), you can allocate memory for your array this way:

    typedef char MyStringType[30];

    void main()
    {
    MyStringType* pArray;
    int max = 10;

    pArray = new MyStringType[max];

    // Do something;

    delete[] pArray;
    }



    This is faster, easier and doesn't fragment your memory so much.

    Greetings
    Jan-Klaas


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured