Declare a 2D Dynamic array
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 17

Thread: Declare a 2D Dynamic array

  1. #1
    Join Date
    Jan 2009
    Posts
    146

    Declare a 2D Dynamic array

    How do I declare a dynamic 2D array and ask the user to input its size? Thanks

  2. #2
    Join Date
    Mar 2001
    Posts
    2,365

    Re: Declare a 2D Dynamic array

    Code:
    cout << "Enter Size 1" << endl;
    cin >> size1;
    cout << "Enter Size 2" <<endl;
    cin >> size 2;
    
    int *parray = new int[size1][size2];
    
    //do stuff with array
    
    delete [] parray;
    Other than that I suggest you use a Hash table or link list of link lists.

    HTH,
    ahoodin
    To keep the plot moving, that's why.

  3. #3
    Join Date
    Apr 1999
    Posts
    27,424

    Re: Declare a 2D Dynamic array

    Quote Originally Posted by Elite Commando View Post
    How do I declare a dynamic 2D array and ask the user to input its size? Thanks
    If you did a simple search on CodeGuru, you would have found many, maybe hundreds of threads answering your question.

    How to declare a dynamic 2 dimensional array is one of the most asked and answered questions.

    Regards,

    Paul McKenzie

  4. #4
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Fairfax, VA
    Posts
    10,888

    Re: Declare a 2D Dynamic array

    Alternatives , each with slightly different properties:

    Code:
    //1
    int **arr2d = new int*[rows];
    for (i = 0; i < rows; i++)
        arr2d[i] = new int[cols];
    
    //and release
    for (i = 0; i < rows; i++)
        delete[] arr2d[i];
    delete[] arr2d;
    
    //2
    std::vector< std::vector<int> > arr2d(rows, std::vector<int>(cols));
    // no need to explicitly release
    
    //3
    std::vector<*int> arr2d(rows);
    std::vector<int> arr2d_data(rows*cols);
    for (i = 0; i < rows; i++)
        arr2d[i] = &arr2d_data[i*cols];

  5. #5
    Join Date
    Jan 2009
    Posts
    146

    Re: Declare a 2D Dynamic array

    Quote Originally Posted by Lindley View Post
    Alternatives , each with slightly different properties:

    Code:
    //1
    int **arr2d = new int*[rows];
    for (i = 0; i < rows; i++)
        arr2d[i] = new int[cols];
    
    //and release
    for (i = 0; i < rows; i++)
        delete[] arr2d[i];
    delete[] arr2d;
    
    //2
    std::vector< std::vector<int> > arr2d(rows, std::vector<int>(cols));
    // no need to explicitly release
    
    //3
    std::vector<*int> arr2d(rows);
    std::vector<int> arr2d_data(rows*cols);
    for (i = 0; i < rows; i++)
        arr2d[i] = &arr2d_data[i*cols];
    Alright Thanks! One more question, suppose I make a matrix by using an array "mat[4][5]" 4 rows and 5 columns and I wish to fill the matrix with random alphabets, how will I do that? Thanks!

  6. #6
    Join Date
    Sep 2004
    Location
    Holland (land of the dope)
    Posts
    4,123

    Re: Declare a 2D Dynamic array

    Use 'rand' (and 'srand') to generate numbers between 1 and 26 and put them in the array.

  7. #7
    Join Date
    Jan 2009
    Posts
    146

    Red face Re: Declare a 2D Dynamic array

    Quote Originally Posted by Skizmo View Post
    Use 'rand' (and 'srand') to generate numbers between 1 and 26 and put them in the array.
    Alright, I know how to use the rand() function, however, I'm not sure about srand() or how Im going to tell the compiler to pick a random number between 1 and 26? or how these numbers will be converted to alphabets? I am very new to c++, Thanks!

  8. #8
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Fairfax, VA
    Posts
    10,888

    Re: Declare a 2D Dynamic array

    Don't worry about srand() for now. The consequence of not using it is merely that you'll get the same sequence of random values on every run of the program, which is actually a good thing in terms of debugging.

    As for picking a random capital letter:
    Code:
    char asciival = (rand() &#37; 26) + 'A';
    See if you can figure out why that works. Hint: % is the integer modulus operator, and a char is merely a 1-byte int that gets treated a bit differently by output operations.

  9. #9
    Join Date
    Mar 2001
    Posts
    2,365

    Re: Declare a 2D Dynamic array

    How to use srand() must be the second most asked question on codeguru and the second most common example in coursepacks and textbooks!

    Any search on google should do!
    ahoodin
    To keep the plot moving, that's why.

  10. #10
    Join Date
    Jan 2009
    Posts
    146

    Re: Declare a 2D Dynamic array

    Quote Originally Posted by Lindley View Post
    Don't worry about srand() for now. The consequence of not using it is merely that you'll get the same sequence of random values on every run of the program, which is actually a good thing in terms of debugging.

    As for picking a random capital letter:
    Code:
    char asciival = (rand() % 26) + 'A';
    See if you can figure out why that works. Hint: % is the integer modulus operator, and a char is merely a 1-byte int that gets treated a bit differently by output operations.
    Thanks! I have yet to figure out how this works, but for some reason it seems to generate only the letter "P", no other letter is generated? why?

  11. #11
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,261

    Re: Declare a 2D Dynamic array

    Quote Originally Posted by Elite Commando
    I have yet to figure out how this works, but for some reason it seems to generate only the letter "P", no other letter is generated? why?
    Post the smallest and simplest compilable program that demonstrates the problem.
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

  12. #12
    Join Date
    Jan 2009
    Posts
    146

    Re: Declare a 2D Dynamic array

    Quote Originally Posted by laserlight View Post
    Post the smallest and simplest compilable program that demonstrates the problem.
    Code:
    char asciival = (rand() % 26) + 'a';
    
    char a[4][5];
    
    
    for(int i=0; i<4; i++)
    {
    	for(int j=0; j<5; j++)
    	{
    	a[i][j]=asciival;
    	cout<<a[i][j];
    	}
    	cout<<endl;
    }
    a simple 4 by 5 matrix with random alphabets is what Im looking for THANKS

  13. #13
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,261

    Re: Declare a 2D Dynamic array

    I get these errors when trying to compile your sample program with the MinGW port of g++ 3.4.5:
    Code:
    test.cpp:1: error: `rand' was not declared in this scope
    test.cpp:6: error: expected unqualified-id before "for"
    test.cpp:6: error: expected constructor, destructor, or type conversion before '<' token
    test.cpp:6: error: expected constructor, destructor, or type conversion before '++' token
    Of course, you can point out to me that I was expected to #include <cstdlib> and place your code snippet in a main function, but I did ask for a compilable program

    Anyway, a possible problem is that you are using the same value (asciival) on every iteration. You probably want to do this instead:
    Code:
    #include <iostream>
    #include <cstdlib>
    #include <limits>
    
    // Generate a portable seed based on system time.
    unsigned int timeSeed()
    {
        using namespace std;
    
        time_t now = time(0);
        unsigned char* p = reinterpret_cast<unsigned char*>(&now);
    
        unsigned int seed = 0;
        unsigned int seed_multiplier = numeric_limits<unsigned char>::max() + 2U;
        for (size_t i = 0; i < sizeof now; ++i)
        {
            seed = seed * seed_multiplier + p[i];
        }
    
        return seed;
    }
    
    int main()
    {
        using namespace std;
        srand(timeSeed());
    
        char a[4][5];
    
        for(int i=0; i<4; i++)
        {
            for(int j=0; j<5; j++)
            {
                a[i][j] = (rand() &#37; 26) + 'a';
                cout<<a[i][j];
            }
            cout<<endl;
        }
    }
    The timeSeed() function is just some code I adapted from this tutorial on using rand().
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

  14. #14
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Fairfax, VA
    Posts
    10,888

    Re: Declare a 2D Dynamic array

    Quote Originally Posted by laserlight View Post
    The timeSeed() function is just some code I adapted from this tutorial on using rand().
    I'm very suspicious of any webpage that claims the uniform distribution and the normal distribution are the same thing.

  15. #15
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,261

    Re: Declare a 2D Dynamic array

    Quote Originally Posted by Lindley
    I'm very suspicious of any webpage that claims the uniform distribution and the normal distribution are the same thing.
    Yes, you are right. Pity I did not catch that bug; I have informed the author of another mistake previously, but in terms of programming she is one of the people that I respect (although ironically the mistake I pointed out had to do with a code snippet).
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

Page 1 of 2 12 LastLast

Posting Permissions

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


Azure Activities Information Page

Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center