2016-03-29 74 views
0

我現在想學習,但發送給我的文件不正確。我試圖修復一些東西,但它開始,然後就會崩潰。我正在學習動態記憶,所以我不知道它。這裏是realloc()的代碼。動態內存中的新功能。 realloc();

#include <stdio.h> /* printf, scanf, NULL */ 

    #include <stdlib.h> /* malloc, free, rand */ 

    int main() 

{ 

int count=0,i; 

int *stations=NULL,*ptrToStations=NULL; 



for(i=1;i<=7;i++,count++) 
    { 

ptrToStations=(int*)realloc(stations,count*sizeof(int)); 

if(ptrToStations!=NULL)//заделили сме памет 

{ stations = ptrToStations; 

ptrToStations[count]=i;} 

    } 

for(i=0;i<7;i++) 

printf("%d",stations[i]); 

printf("\n"); 



//добавяне на 8 елемент 

ptrToStations=(int*)realloc(stations,++count*sizeof(int)); 

if(ptrToStations!=NULL)//заделили сме памет 

{ stations = ptrToStations; 

ptrToStations [count-1]=count;} 



for(i=0;i<count;i++) 

printf("%d",stations[i]); 

printf("\n"); 

int x=3; 

//преместваме елементите с един назад 

for(i=x;i<count;i++) 


ptrToStations[i-1]=ptrToStations[i]; 

//премахване на 8 елемент 

ptrToStations=(int*)realloc(stations,--count*sizeof(int)); 

if(ptrToStations!=NULL)//заделили сме памет 



stations = ptrToStations; 



for(i=0;i<count;i++) 


printf("%d",stations[i]); 

printf("\n"); 


free (ptrToStations); 

free (stations); 

return 0; 

} 
+0

代碼註釋應該是英文 –

回答

0

這裏

  1. 雙自由到底相同的內存塊的
  2. 數應在第一次迭代與1 Overwise開始你有幾個問題,你試圖改變的大小0字節的存儲器塊
  3. 數組越界錯誤 ptrToStations [count] = i;

你的代碼實際上是這個樣子

#include <stdio.h> /* printf, scanf, NULL */ 

    #include <stdlib.h> /* malloc, free, rand */ 

    int main() 

{ 

int count=1,i; 

int *stations=NULL,*ptrToStations=NULL; 



for(i=1;i<=7;i++,count++){ 

    ptrToStations=(int*)realloc(stations,count*sizeof(int)); 

    if(ptrToStations != NULL) { 
     stations = ptrToStations; 
     ptrToStations[count-1]=i; 
     for(i=0;i<count;i++) 
      printf("%d",stations[i]); 
     printf("\n"); 
    } 
} 





//добавяне на 8 елемент 

ptrToStations=(int*)realloc(stations,++count*sizeof(int)); 

if(ptrToStations!=NULL){ 
    stations = ptrToStations; 
    ptrToStations [count-1]=count; 
    } 



for(i=0;i<count;i++) 
    printf("%d",stations[i]); 
printf("\n"); 

int x=3; 

//преместваме елементите с един назад 

for(i=x;i<count;i++) 
    ptrToStations[i-1]=ptrToStations[i]; 

//премахване на 8 елемент 

ptrToStations=(int*)realloc(stations,--count*sizeof(int)); 

if(ptrToStations!=NULL) { 
    stations = ptrToStations; 
    for(i=0;i<count;i++) 
     printf("%d",stations[i]); 
printf("\n"); 
} 


free (stations); 

return 0; 

}