2d数组的动态内存分配,其中列的大小不同

vis*_*mar 0 c++ arrays 2d

我想用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
Run Code Online (Sandbox Code Playgroud)

我能够以上述方式创建二维数组,但如何显示数组内容不断为我创建一个问题.请有人解释我如何解决这个问题.

Anm*_*ggi 5

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

但是,如果由于某种原因你不想使用向量并且想要使用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];
    }
}  
Run Code Online (Sandbox Code Playgroud)

但是,建议不要这样做,因为它可能会导致很多问题(例如,如果忘记使用delete后发生内存泄漏new).如果您事先不知道数组的大小,请更喜欢使用向量.