Multi-dimensional array and pointers in C++?

后端 未结 6 1506
悲哀的现实
悲哀的现实 2020-12-20 09:35
int *x = new int[5]();

With the above mentality, how should the code be written for a 2-dimensional array - int[][]?

i         


        
相关标签:
6条回答
  • 2020-12-20 10:02

    You can do the initializations separately:

    int **x = new int*[5];
    for(unsigned int i = 0; i < 5; i++)
        x[i] = new int[5];
    
    0 讨论(0)
  • 2020-12-20 10:04

    This is how you do it:

    int (*x)[5] = new int[7][5] ;
    

    I made the two dimensions different so that you can see which one you have to use on the lhs.

    0 讨论(0)
  • 2020-12-20 10:09

    There are several ways to accomplish this:

    • Using gcc's support for flat multidimensional arrays (TonyK's answer, the most relevant to the question IMO). Note that you must preserve the bounds in the array's type everywhere you use it (e.g. all the array sizes, except possibly the first one), and that includes functions that you call, because the produced code will assume a single array. The allocation of $ new int [7][5] $ causes a single array to be allocated in memory. indexed by the compiler (you can easily write a little program and print the addresses of the slots to convince yourself).

    • Using arrays of pointers to arrays. The problem with that approach is having to allocate all the inner arrays manually (in loops).

    • Some people will suggest using std::vector's of std::vectors, but this is inefficient, due to the memory allocation and copying that has to occur when the vectors resize.

    • Boost has a more efficient version of vectors of vectors in its multi_array lib.

    In any case, this question is better answered here: How do I use arrays in C++?

    0 讨论(0)
  • 2020-12-20 10:13

    Ff the array has predefined size you can write simply:

    int x[5][5];
    

    It compiles

    If not why not to use a vector?

    0 讨论(0)
  • 2020-12-20 10:15

    There is no new[][] operator in C++. You will first have to allocate an array of pointers to int:

    int **x = new int*[5];
    

    Then iterate over that array. For each element, allocate an array of ints:

    for (std::size_t i = 0; i < 5; ++i)
        x[i] = new int[5];
    

    Of course, this means you will have to do the inverse when deallocating: delete[] each element, then delete[] the larger array as a whole.

    0 讨论(0)
  • 2020-12-20 10:27

    I prefer doing it this way:

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

    and then I just index the array by 5 * row + col.

    0 讨论(0)
提交回复
热议问题