Video: Koj puas xav tau malloc hauv C ++?
2024 Tus sau: Lynn Donovan | [email protected]. Kawg hloov kho: 2023-12-15 23:47
Koj siv malloc thaum koj xav tau los faib cov khoom ntawd yuav tsum muaj nyob dhau lub neej ntawm kev ua tiav ntawm qhov thaiv tam sim no (qhov twg luam tawm-rau-rov qab yuav yuav kim ib yam), los yog koj yuav tsum faib lub cim xeeb ntau dua qhov loj ntawm pawg ntawd (piv txwv li: 3mb hauv zos pawg array yog lub tswv yim phem).
Tsis tas li, koj puas xav tau malloc hauv C ++?
Qhov txawv yog yooj yim: malloc allocates nco, thaum tshiab allocates nco THIAB hu tus constructor ntawm cov khoom koj 're allocating nco rau. Yog li, tshwj tsis yog koj raug txwv rau C, koj yuav tsum yeej tsis siv malloc , tshwj xeeb tshaj yog thaum nrog C++ khoom.
Ib tug kuj yuav nug, dab tsi yog lub ntsiab lus ntawm malloc? Hauv C, lub tsev qiv ntawv muaj nuj nqi malloc yog siv los faib ib lub cim xeeb ntawm lub heap. Qhov kev pab cuam nkag mus rau qhov thaiv ntawm lub cim xeeb ntawm tus taw tes uas malloc rov qab los. Thaum lub cim xeeb tsis xav tau lawm, tus pointer raug xa mus rau dawb uas deallocates lub cim xeeb kom nws tuaj yeem siv rau lwm lub hom phiaj.
Hauv qhov no, puas muaj malloc hauv C ++?
Lub malloc () ua haujlwm hauv C++ faib a thaiv ntawm uninitialized nco thiab rov qab a void pointer rau tus ib byte tus allocated nco thaiv yog tus kev faib ua tiav. Yog tus qhov loj yog xoom, tus tus nqi rov qab nyob ntawm tus kev siv ntawm tus tsev qiv ntawv. Nws tej zaum los tsis yog a null pointer.
Yuav ua li cas koj malloc ib tug qauv?
Rau qhov koj xav tau koj xav tau ob malloc () s. qauv vector *y = malloc (loj * y); /* Nco ntsoov tus pointer */ y->x = calloc(10, sizeof *y->x); Hauv thawj kab, koj faib lub cim xeeb rau cov khoom Vector. malloc () rov qab tus taw tes rau lub cim xeeb faib, yog li y yuav tsum yog Vector pointer.