Thread: 2 dimentional array

  1. #1
    Registered User
    Join Date
    Jun 2003
    Posts
    1

    2 dimentional array

    Hello. I recently started to learn c++ again and started from the beginning. I've been trying to create a 2 dimentional array that would allocate memory during the runtime and came up with something like this:
    int **array;
    array = new int* [6];
    I'm not even sure what I exactly created, but seems to work as a 2 dimentional array.
    I tried to send this array as an argument to a void function i created but the compiller gives me an error. What are the right methods?

  2. #2
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Beware, you're creating an array of 6 int*, not a two-dimensional array.
    Remember, a two-dimensional array is name[dim1][dim2].
    As to how to create a two-dimensional array on the heap, I'm at a loss. I can't find the syntax for it.
    Last edited by Elysia; 11-10-2007 at 11:44 PM.

  3. #3
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    You create a 2-dimensional array using the knowledge you already have about creating a 1-dimensional array. As you've started doing, you create a 1D array of 1D arrays.
    First you make a variable to hole the array of arrays: done.
    Next you create the array to hold the other arrays and assign that to the variable: done.
    Next you create all those other arrays and assign them to the positions in the array: NOT done.
    It helps a lot if you typedef the kind of pointer that goes in the first array.

    So you're just missing the loop that creates all those actual data arrays. You already have the array to hold them all. Think you can finish it now?

    btw this kind of array even allows for the secondary arrays to be of differing lengths.

    Now the other way to create a 2-D array of m*n items is to simply create an array that is m*n big. Then you step across in multiples of m to go down by one n. That's how bitmaps do it too. This method is usually preferred because it is more efficient. However, unlike the other method, this way you can't use the array[m][n] syntax. Instead it's better to make a function to to the lookups, and then you get the even better syntax of: lookup(m, n).
    Last edited by iMalc; 11-11-2007 at 12:24 AM.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  4. #4
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    If you're using a pointer to the array, it is very possible to do [x][y], since the compiler just calculates the offset.
    From the above info, I'd suggest the easiest way to create a 2D array is just to create a single dimension array with all elements (x * y) and use a pointer to that array, so you can use 2D syntax.

  5. #5
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    Quote Originally Posted by Elysia View Post
    If you're using a pointer to the array, it is very possible to do [x][y], since the compiler just calculates the offset.
    From the above info, I'd suggest the easiest way to create a 2D array is just to create a single dimension array with all elements (x * y) and use a pointer to that array, so you can use 2D syntax.
    No, you can't do that. Each [] operator is a dereference. It only works for the first method I described precisely because there are 2 dereferences involved. In the second case there is only 1 dereference, so it cannot work.

    Don't feel you're obliged to give advice when you don't know the subject matter. As you've already stated you don't know about this stuff, which is perfectly fine. Feel free to ask questions of course. The more you learn, the more you realise you don't know, as they say.

    Actually here's one for ya: Did you know that if you have a pointer 'a' and an integer 'i', that i[a] is the same as a[i]?!
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

  6. #6
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    I'm working from my knowledge of pointers... OK, so it's not possible. I didn't know that, I never actually tried. But a[10] works, nevertheless, and which just compiles to a + sizeof(a) * 10. So why wouldn't 2D work?
    Unless, of course, there is a way to cast that pointer to a type that is a 2D-pointer.
    I disgress. Sometimes others can fill out what someone else cannot. We aren't perfect.

    Otherwise, it's possible to do
    Code:
    *(p + sizeof(p) * x * y) = y
    Or
    Code:
    int& array(int* p, int x, int y) 
    {
    	return *(p + sizeof(p) * x * y); 
    }
    int main() 
    {
    	int* p = new int[100];
    	array(p, 10, 2) = 50;
    }
    Last edited by Elysia; 11-11-2007 at 01:06 AM.

  7. #7
    The larch
    Join Date
    May 2006
    Posts
    3,573
    I think 2D won't work because the compiler cannot know how large the dimensions are. If you allocate an array of 20 ints, how is the compiler supposed to know whether you are using it as array[2][10] or array[4][5] (or other combinations)?

    Another easy way to create 2D arrays is to use a std::vector of std::vectors:
    Code:
    std::vector<std::vector<int> > vec2d(dim1, std::vector<int>(dim2));
    This line would take care of all the complicated memory allocations in the original approach. And the vector would deallocate all memory automatically when it goes out of scope.

    It looks ugly but typedefs can improve that. And you don't need to create a "rectangular" array when you start but you can add subarrays of arbitrary length at any time.
    Last edited by anon; 11-11-2007 at 05:49 AM.
    I might be wrong.

    Thank you, anon. You sure know how to recognize different types of trees from quite a long way away.
    Quoted more than 1000 times (I hope).

  8. #8
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    But a[10] works, nevertheless, and which just compiles to a + sizeof(a) * 10.
    No, it compiles to *(a + sizeof(a) * 10). Thus, a[10][4] compiles to *(*(a + sizeof(a) * 10) + sizeof(*a) * 4), and if a is an int*, the second dereference is invalid.

    Just use Boost.MultiArray.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  9. #9
    Malum in se abachler's Avatar
    Join Date
    Apr 2007
    Posts
    3,195
    Boost is a huge POS, honestly I dont know why people recommend it to beginners (or anyone else), as it will only confuse them and keep them from learning the fundamentals. The guy is obviously trying to learn how to use pointers, creating the actual array is secondary to that goal. Boost is irrelevant here, since it wont teach him how to use pointers.

  10. #10
    Cat without Hat CornedBee's Avatar
    Join Date
    Apr 2003
    Posts
    8,895
    1) Anyone calling Boost a POS is earning a lot of negative points in my book.

    2) The thread is called "2 dimentional array", and spelling aside, this looks like a request for a 2-dimensional array to me.

    3) I consider multi-dimensional arrays a really bad way of learning pointers.
    All the buzzt!
    CornedBee

    "There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
    - Flon's Law

  11. #11
    Registered User
    Join Date
    Apr 2006
    Posts
    2,149
    Quote Originally Posted by iMalc View Post
    Now the other way to create a 2-D array of m*n items is to simply create an array that is m*n big. Then you step across in multiples of m to go down by one n. That's how bitmaps do it too. This method is usually preferred because it is more efficient. However, unlike the other method, this way you can't use the array[m][n] syntax. Instead it's better to make a function to to the lookups, and then you get the even better syntax of: lookup(m, n).
    If you know the dementions of the array at compile time you can do The following. Array 2dRef will work just like a 2d array. Unfortunately, this has limited usefulness since the prime reason for using a heap array in the first place is to have the size be runtime dependent.
    Code:
        int *array1d=new int[m*n];
        int (*array2dptr)[m][n] = (int (*)[m][n])(array1d);
        int (&array2dRef)[m][n]=*array2dptr;
        //usage example
        array2dRef[7][2]=0;
        ...
        delete &array2dRef;
    You can also make m runtime dependant:(let n=4 in this example)
    Code:
        char *array1d=new char[m*4];
        char (*array2d)[4] = (char(*)[4])(array1d);
        //usage example
        array2d[7][2]='0';
        ...
        delete array2d;
    Last edited by King Mir; 11-11-2007 at 01:39 PM.
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. array of pointers/pointer arithmetic
    By tlpog in forum C Programming
    Replies: 18
    Last Post: 11-09-2008, 07:14 PM
  2. Have problems with copying my array!
    By AvaGodess in forum C Programming
    Replies: 11
    Last Post: 09-25-2008, 12:56 AM
  3. passing 3 dimentional array into function
    By 182blink in forum C Programming
    Replies: 3
    Last Post: 10-28-2006, 05:20 PM
  4. Class Template Trouble
    By pliang in forum C++ Programming
    Replies: 4
    Last Post: 04-21-2005, 04:15 AM
  5. Quick question about SIGSEGV
    By Cikotic in forum C Programming
    Replies: 30
    Last Post: 07-01-2004, 07:48 PM