簡體   English   中英

列大小不同的二維數組的動態內存分配

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

我想用C ++語言動態創建一個二維數組。 但是在那個二維數組中,列的大小應該不同。 我的意思是說二維數組不應該在M * N中。

它應該像...。

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

我能夠以上述方式創建2d數組,但是如何連續顯示數組內容對我來說卻是一個問題。 請任何人解釋我如何提出這個問題。

最好的方法是使用vectors 它們是可調整大小的陣列,可自動處理所有內存管理。 在這種情況下,您可以創建一個二維矢量。

但是,如果由於某種原因您不想使用向量,而是想使用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 )。 如果您事先不知道數組的大小,則最好使用向量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM