简体   繁体   English

列大小不同的二维数组的动态内存分配

[英]dynamic memory allocation of 2d array in which columns are of different size

i want to create a 2d array dynamically in c++ language. 我想用C ++语言动态创建一个二维数组。 But in that 2d array columns should be of different size. 但是在那个二维数组中,列的大小应该不同。 i mean to say that 2d array should not be in M * N. 我的意思是说二维数组不应该在M * N中。

It should be something like.... 它应该像...。

1 2 next line
3 4 5 next line
2 3 4 5 next line
5 next line
4 5 7

I am able to create 2d array in above manner but how to display content of array continously create a problem for me. 我能够以上述方式创建2d数组,但是如何连续显示数组内容对我来说却是一个问题。 Please anyone explain me how to come up with this problem. 请任何人解释我如何提出这个问题。

The best way to do this will be by using vectors . 最好的方法是使用vectors They are resizable arrays which handle all the memory management automatically. 它们是可调整大小的阵列,可自动处理所有内存管理。 In this case, you can create a 2-D vector. 在这种情况下,您可以创建一个二维矢量。

However, if for some reason you do not want to use vectors and want to use C-style arrays, then you can do it by creating an array of pointers and allocating different amounts of memory to each one of them. 但是,如果由于某种原因您不想使用向量,而是想使用C样式的数组,则可以通过创建一个指针数组并为每个指针分配不同的内存量来做到这一点。 For storing their size, we can follow the strategy of allocating an additional cell in every array which will store the size of that array. 为了存储它们的大小,我们可以遵循在每个数组中分配一个额外单元格的策略,该数组将存储该数组的大小。

int main()
{
    const int no_of_arrays=10;
    int array_size[no_of_arrays]= {1,4,2,4,3,6,8,9,1,3}; // Different size for each array
    int *p[no_of_arrays];  // An array of pointers
    for(int i=0; i<no_of_arrays; i++)
    {
        p[i]=new int[array_size[i]+1];  // Allocating
        p[i][0]=array_size[i];  // The first cell holds the size of the array
        for(int j=1; j<=p[i][0]; j++)
        {
            p[i][j]=10;  // Fill the array with the desired values;
        }
    }

    // Display the arrays
    for(int i=0; i<no_of_arrays; i++)
    {
        for(int j=1; j<=p[i][0]; j++)
        {
            std::cout<<p[i][j]<<" ";
        }
        std::cout<<"\n";
    }

    /*
     *
     * Do your thing with the arrays.
     *
     */

    // Deallocate the memory allocated to the arrays
    for(int i=0; i<no_of_arrays; i++)
    {
        delete[] p[i];
    }
}  

However, doing this is not recommended as it can cause lot of problems ( For example memory leaks in case you forget to use delete after new ). 但是, 不建议这样做,因为这会导致很多问题(例如,内存泄漏,以防您在new之后忘记使用delete )。 Prefer to use vectors instead in case you don't know the size of the array beforehand. 如果您事先不知道数组的大小,则最好使用向量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM