You are on page 1of 4

NguyenNamHungs Weblog

Thng Mi 31, 2009

Cp pht ng trong C++


Filed under: Lp trnh C/C++ nguyennamhung @ 4:15 chiu

Chuyn mc: Cng ngh thng tin Lp trnh C/C++ Cuc sng

hiu cp pht ng l g ta nn hiu li ch ca n: Li ch th 1: Xt 2 on chng trnh sau: Trng hp cp pht tnh: M: void main(){ int a[100];//Cp pht tnh 100 nh 4 bytes lin tip nhau lu tr mng nguyn a, y bin a l 1 bin con tr tr vo nh u tin. Sudunga(); int b;//Cp pht tnh 1 nh 4 bytes lu tr bin nguyn b Sudungb(); } Khi cp pht tnh cc nh b chim gi v ch c gii phng khi kt thc chng trnh.Trong sut qu trnh chy chng trnh lun chim 4+4*100=404 bytes trn RAM,RAM ch c gii phng khi chng trnh kt thc. Trng hp cp pht ng: M: void main(){

Uncategorized Tm kim:

Tm kim Lu tr: Thng Mt 2010 Thng Mi Hai 2009 Thng Mi 2009 Thng Tm 2008 Thng T 2008 Meta: ng k ng nhp Dng thng tin Dng thng tin cc phn hi. XFN W ordPress.com

int *a=new int[100];//Cp pht ng 100 nh 4 bytes lin tip nhau lu tr mng nguyn a, y bin a l 1 bin con tr tr vo nh u tin. Sudunga(); delete []a; int *b=new int;//Cp pht ng 1 nh 4 bytes lu tr,bin con tr b tr vo nh ny Sudungb(); } Khi cp pht ng t u chng trnh n ht hm Sudunga() chng trnh chim 4*100=400 bytes trn RAM, Sau ton t delete n trc dng khai bo bin con tr b, RAM c gii phng, t dng con tr b n ht hm Sudungb() chng trnh chim 4 bytes trn RAM,kt thc chng trnh RAM c gii phng. Li ch th 2: Gi s ta cn vit chng trnh c 1 mng nguyn vi s phn t n ca mng cho ngi dng nhp vo: Nu dng cp pht tnh: M: void main(){ int n; cout<<Nhap n:; cin>>n; int a[n]; } Khi bin dch chng trnh s bo li a::unknow size v khi cp pht tnh 1 mng, mng phi c chiu di khng i(khng th gn bin vo dng khai bo trong cp pht tnh c). Gii php tnh hung: M: void main(){ int n; cout<<Nhap n:; cin>>n; int a[100];

} Lc ny chng trnh c th p ng c khi ngi dng mun nhp vo mng <=100 phn t,nu ngi dng nhp hn 100 phn t s khng c khng gian lu tr bin=>Chng trnh b gii hn Nu dng cp pht ng: M: void main(){ int n; cout<<Nhap n:; cin>>n; int *a=new int[n]; .. } Lc ny nu ngi dng khai bo n=100 ta s c mng 100 phn t, n=1000 ta s c mng 1000 phn t. Vy n bng bao nhiu th chng trnh khng chy c, Ty thuc vo dung lng RAM ca h thng. Gi s h thng c 2GB RAM th c th lu tr hn 5*(10^8) phn t. Tt nhin li ch ca cp pht ng cn nhiu nhng tm thi ch nh 2 ci ny
About these ads

Be the first to like this.

li phn hi

li phn hi

Cha c phn hi. RSS cho phn hi ca bi vit ny. URL TrackBack

Gi phn hi

Enter your comment here...

Theme: Rubric. Blog at WordPress.com.

Follow