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

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

本文关键字:二维数组 动态 内存 分配      更新时间:2023-10-16

我想用c++语言动态创建一个2d数组。但在二维数组中,列的大小应该不同。我的意思是说2d数组不应该在M * n

应该是....

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

我能够以上述方式创建2d数组,但如何显示数组的内容不断为我创建一个问题。谁来给我解释一下这个问题是怎么解决的?

最好的方法是使用向量。它们是可调整大小的数组,可以自动处理所有内存管理。在这种情况下,您可以创建一个二维矢量。

然而,如果出于某种原因你不想使用向量,而想使用c风格的数组,那么你可以通过创建一个指针数组并为每个指针分配不同数量的内存来实现。为了存储它们的大小,我们可以遵循在每个数组中分配一个额外单元格的策略,该单元格将存储该数组的大小。

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];
    }
}  
但是,不建议使用这样做,因为这会导致很多问题(例如,如果您在new之后忘记使用delete,则会导致内存泄漏)。如果事先不知道数组的大小,最好使用vector