在C中具有變量數組大小的動態數組分配
varible sized數組,也稱為動態數組,在標準的C中提出了挑戰。請考慮以下程序。 0; file*圖片; while(!feof(picture)){
n = fread(sbuf,sizeof(char),siz,picture); / * ...用緩衝區做事... */ /* memset(sbuf,0,sizeof(sbuf)); */試圖分配一個由變量SIZ確定的大小的字符。但是,在標準C中,陣列大小必須是常數。 This poses the question: how can we declare siz correctly to allow code compilation?
Unfortunately, there is no direct method to declare an array with a variable size in standard C. However, several alternatives exist:
In modern C , the std::vector container can be used as a flexible alternative to數組。它可以很容易地擴展到任何所需的大小,並且其用法相對簡單。
新運算符:
可以使用新操作員在堆上動態分配內存。要創建具有可變大小的數組,可以使用char* sbuf = new char [siz];在堆上分配一系列SIZ字符。但是,這種方法引入了內存管理問題(例如,潛在的內存洩漏),使其不適合STD :: vector。
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3