2D arrays, size allocated at run time?

This is a discussion on 2D arrays, size allocated at run time? within the C++ Programming forums, part of the General Programming Boards category; Hello, I am looking to create a 2D array of weights, however I need the dimentions to be specified at ...

  1. #1
    Registered User
    Join Date
    Sep 2010
    Location
    London
    Posts
    41

    2D arrays, size allocated at run time?

    Hello,

    I am looking to create a 2D array of weights, however I need the dimentions to be specified at runtime. I've coded the following which is not working:

    Code:
    ....
    cin >> x;
    cin >> n;
    float weightTable[x][n];
    It is not letting me saying that expression must have a constant value.

    How should I do it?

    Thank you very much

  2. #2
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,533
    Code:
    float **weightTable = new float*[x];
    for ( i = 0 ; i < x ; i++) weightTable[i] = new float[n];
    A better idea would be to use std::vector, then you don't have to manage memory yourself.

    Don't forget to free the memory - each [i] first, then the whole thing.
    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.

  3. #3
    Registered User
    Join Date
    Sep 2010
    Location
    London
    Posts
    41
    Hi,

    OK thank you. I am not too used to pointers, think will just go for a 2D vector.

    Thank you very much,

  4. #4
    Registered User
    Join Date
    Sep 2010
    Posts
    33
    Hi Kat, Iím learning c++ so all this is new to me, and if you can do this with vectors then you know more than me.

    However, if youíre still stuck, then Salemís perfectly presented code above is intuitively very simple.

    ďOne of the main usages of a pointers is for heap memory allocation. The benefit of heap allocation is that you manage when the data is created, how long it exists, and the size is defined at run-time.Ē

    ďIn C++ use the new (data type)[ [size of elements] ] keyword to allocate data. Note that unlike the C function malloc(), the new keyword allocates sizes by calculating the needed bytes itself. Use the delete keyword to release data. Do not forget to use the delete[] keyword when releasing an array of data.Ē


    So, for a one-dimensional array:

    Code:
    float *WeightTable;
    int x = 10;  
    WeightTable = new float[x];
    
    //Testing
    WeightTable[0] = 1.234;
    WeightTable[9] = 5.678;
    cout << WeightTable[0] << endl; //prints 1.234
    cout << WeightTable[9] << endl; //prints 5.678
    
    delete WeightTable; // clear memory
    And for a two dimensional array:

    Code:
    float **WeightArray; 
    int Rows;
    int Cols;
    
    Rows = 8;
    Cols = 9;
    
    WeightArray = new float*[Rows];
    for (int i = 0; i < Rows; i++) 
    	WeightArray[i] = new float[Cols];
    
    // Testing
    WeightArray[0][0] = 1.234;
    WeightArray[7][8] = 5.678;
    cout << WeightArray[0][0] << endl;
    cout << WeightArray[7][8] << endl;
    
    
    // loop to delete WeightArray[Rows][Cols]
    Intuitive note:

    For 1D array there is one *, and after the new keyword there are no *ís.

    For a 2D array there are 2 *ís, and after the new keyword there is one *, and no *ís after the second occurrence of the new keyword

  5. #5
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,594
    delete should be matched with delete [] since you're using new[]. But you really shouldn't mess around with that stuff in C++. If you do, you should use smart pointers.
    Alternatively, here's how to do it easier:

    Code:
    std::vector<std::vector<int>> v(x, std::vector(y));
    There is also boost::multiarray which makes this easier. It's part of the boost library which you can find at their homepage.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  6. #6
    Registered User
    Join Date
    Sep 2010
    Posts
    33
    Thank you Elysia, Iím glad you responded; I wouldnít want to promote any dubious practises.

    Although I intuitively understood the above code, I wasnít intuitively happy with it. The code you posted looks much more solid and appealing.

    So, Iíll add vectors to my growing list then.

  7. #7
    Super Moderator VirtualAce's Avatar
    Join Date
    Aug 2001
    Posts
    9,596
    delete should be matched with delete [] since you're using new[]. But you really shouldn't mess around with that stuff in C++.
    I would argue you should at least know how to 'mess around' with this stuff in C++ long before you begin poking around in the STL and create thousands of memory leaks b/c you aren't cleaning up containers correctly. Directing people away from memory management is good for those who already understand it and a huge disservice to those who don't. Memory management is a key part of C++ and if you cannot do it correctly then you should not be using the language. Yes we have abstractions now that make our lives easier but most of us who use them completely understand the concepts behind them b/c we used to have to do the very things they provide for us. Plain and simple in C or C++ is that you should know how to manage memory.

    I would also argue that if you start using the STL before you know how to manage memory that you more than likely create more memory leaks than simply creating a few arrays on the heap that you don't clean up. It is so easy to push_back hundreds of pointers into a vector and if you really don't understand why you need to clean them up you will have created hundreds of memory leaks.
    Last edited by VirtualAce; 09-18-2010 at 11:15 AM.

  8. #8
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,594
    I disagree. You should know how to handle the concepts fully, but that is different from understanding and being able to do memory allocation manually.
    Simply put, you should know that everything that comes from new must be deleted and know what tools there are that handles this deallocation for you. You should also know the difference between pointers, references and normal objects on the stack.

    Besides that, throwing people into knowing this low-level stuff before learning to use STL is ridiculous IMO. You have the tools. Use them. If and only if you need to roll our your own solution, then should you learn the low-level tools. By then, you should be familiar with the high-level tools so that you can effectively use them together with the low-level tools when rolling out your own solutions.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  9. #9
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    21,717
    Quote Originally Posted by Bubba
    I would argue you should at least know how to 'mess around' with this stuff in C++ long before you begin poking around in the STL and create thousands of memory leaks b/c you aren't cleaning up containers correctly.
    I agree, but you do not have to learn how to implement containers in order to learn how to use them.

    Quote Originally Posted by Bubba
    I would also argue that if you start using the STL before you know how to manage memory that you more than likely create more memory leaks than simply creating a few arrays on the heap that you don't clean up. It is so easy to push_back hundreds of pointers into a vector and if you really don't understand why you need to clean them up you will have created hundreds of memory leaks.
    It is a misconception that storing a pointer in a vector always means that the vector has ownership of the object that the pointer points to. But even if we suppose that the vector does have ownership of the object, why would the student store pointers in the vector with that intention, when he/she has not been taught about manual memory management?

    As demonstrated by Accelerated C++, the course of study can be such that students are only taught manual memory management when they are ready to learn how to implement RAII. Hence, they have no reason to try and mix up incorrect manual memory management with containers from the standard library. This matches Stroustrup's recommendation of an approach that "presents code relying on relatively high-level libraries before going into the lower-level details (necessary to build those libraries)", as stated in his essay on Learning Standard C++ as a New Language (PDF document).
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. size of allocated array
    By boxden in forum C Programming
    Replies: 10
    Last Post: 06-28-2010, 04:45 PM
  2. help with arrays
    By chilledmilk in forum C++ Programming
    Replies: 1
    Last Post: 05-06-2010, 10:32 PM
  3. How to create and manipulate Terabyte size Arrays with Win32API
    By KrishnaPG in forum Windows Programming
    Replies: 1
    Last Post: 11-05-2009, 03:08 AM
  4. Trouble with DMA Segmentation Faults
    By firestorm717 in forum C Programming
    Replies: 2
    Last Post: 05-07-2006, 09:20 PM
  5. Replies: 11
    Last Post: 03-25-2003, 04:13 PM

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